OkHttp是Square开源的轻量级框架,是一款现代、高效、快速的Android版Http client。
它的设计和实现的首要目标便是高效,有如下特性:
• 支持SPDY、连接池、Gzip和Http缓存(记住第一条可直接推及记起下面四条,感觉萌萌哒_);
• 支持SPDY,因此可以同一IP多个连接共享同一个socket(SPDY并不是一种用于替代HTTP的协议,而是对HTTP协议的增强,具体请自行百度);
• 在Http/2不可用时, 连接池可极大减少延时;
• 支持Gzip压缩响应体,降低传输内容的大小;
• 支持Http缓存,避免重复请求;
• 服务器配置多IP情况下,当前IP请求失败,支持自动切换到其他IP;
• 使用Okio来简化数据的访问与存储,提高性能;
• OkHttp还处理了代理服务器问题和SSL握手失败问题;
OkHttp主要支持以下使用方式(记住多少算多少吧):
• 异步get请求;
• 异步post请求;
• 异步文件上传;
• 异步文件下载;
• 异步上传Multipart文件;(多种类型文件合在一起,同一个请求上传)
• 上传下载的进度回调;
• 加载图片;
• 支持请求回调,直接返回对象、对象集合;
• 支持session的保持;
• 支持自签名网站https的访问,提供方法设置下证书就行;
• 支持取消某个请求;
• 是消息回来需要切到主线程,主线程要自己去写。
• 调用比较复杂,需要自己进行封装。
• 缓存失效:网络请求时一般都会获取手机的一些硬件或网络信息,比如使用的网络环境。同时为了信息传输的安全性,可能还会对请求进行加密。在这些情况下OkHttp的缓存系统就会失效了,导致用户在无网络情况下不能访问缓存。
缓存失效解决方案:先过滤可变参数,然后进行手动缓存;不要使用随网络状态变化的参数;
添加网络权限
<uses-permission android:name="android.permission.INTERNET" />
添加okhttp以及Facebook的拦截器(Facebook的拦截器需要),可以在谷歌浏览器里看到请求以及返回的各种数据
api 'com.facebook.stetho:stetho-okhttp3:1.5.0'
api 'com.facebook.stetho:stetho:1.5.0'
1)、先写请求接口回调
package activemq.xmg.com.myapplication;
/**
* @name My Application
* @class name:activemq.xmg.com.myapplication *
* @class describe *配合OkHttpUtil使用的回调接口
* @anthor chuangcui 邮箱:[email protected]
* @time 4/15/21 10:35 AM
*/
public interface OkHttpCallback {
void onSuccess(String response);
void onFailure(String errorMsg);
}
2)、下载文件回调
package activemq.xmg.com.myapplication;
import java.io.File;
/**
* @name My Application
* @class name:activemq.xmg.com.myapplication *
* @class describe *okhttp下载文件的接口
* @anthor chuangcui 邮箱:[email protected]
* @time 4/15/21 10:35 AM
*/
public interface OkHttpDownCallBack {
void onDownSuccess(File file);
void onDownloading(long total,long current);
void onDownFailed(String msg);
}
3)、封装请求工具类
package activemq.xmg.com.myapplication;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import com.facebook.stetho.okhttp3.StethoInterceptor;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import okhttp3.Cache;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
/**
* @name My Application
* @class name:activemq.xmg.com.myapplication *
* @class describe *
* @anthor chuangcui 邮箱:[email protected]
* @time 4/15/21 10:35 AM
*/
public class OkHttpUtil {
public static final MediaType MEDIA_TYPE_MARKDOWN
= MediaType.parse("text/x-markdown; charset=utf-8");
private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/jpeg; charset=utf-8");
private static OkHttpUtil instance;
private OkHttpClient client;
private Context context;
private Handler mHandler;
public static OkHttpUtil getInstance() {
if (instance == null) {
instance = new OkHttpUtil();
}
return instance;
}
/**
* 全局初始化
*
* @param context
*/
public void init(Context context) {
this.context = context;
File sdcache = context.getApplicationContext().getExternalCacheDir();
int cacheSize = 200 * 1024 * 1024;
OkHttpClient.Builder builder = new OkHttpClient.Builder()
.connectTimeout(60, TimeUnit.SECONDS)
.writeTimeout(60, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS);
if (BuildConfig.DEBUG) {
builder.addNetworkInterceptor(new StethoInterceptor());
}
if (sdcache != null) {
builder.cache(new Cache(sdcache.getAbsoluteFile(), cacheSize));
}
client = builder.build();
mHandler = new Handler(Looper.getMainLooper());
}
/**
* 同步GET
*
* @param url
* @param okHttpCallback
* @return
*/
public boolean doSynchronizationGet(String url, final OkHttpCallback okHttpCallback) {
Request request = new Request.Builder().
method("GET", null).
url(url).
build();
Call call = client.newCall(request);
try {
Response response = call.execute();
if (response.code()!=200){
mHandler.post(new Runnable() {
@Override
public void run() {
okHttpCallback.onFailure(call.toString());
}
});
}else {
final String str = response.body().string();
try {
JSONObject jsonObject = new JSONObject(str);
// if (TextUtils.equals(jsonObject.optString("code"), "5")) {
// Intent intent = new Intent(context, LoginActivity.class);
// intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// context.startActivity(intent);
// EnterCheckUtil.getInstance().outLogin();
// return;
// }
} catch (JSONException e) {
e.printStackTrace();
}
mHandler.post(new Runnable() {
@Override
public void run() {
okHttpCallback.onSuccess(str);
}
});
}
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
/**
* 异步GET(同步方法需要放在异步线程里面去执行,主线程无法执行同步方法)
*
* @param url
* @param okHttpCallback
* @return
*/
public boolean doAsyncGet(String url, final OkHttpCallback okHttpCallback) {
if (TextUtils.isEmpty(url) || okHttpCallback == null) {
return false;
}
Request.Builder builder = new Request.Builder().url(url);
builder.method("GET", null);
Request request = builder.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(final Call call, IOException e) {
mHandler.post(new Runnable() {
@Override
public void run() {
okHttpCallback.onFailure(call.toString());
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String str = response.body().string();
try {
JSONObject jsonObject = new JSONObject(str);
// if (TextUtils.equals(jsonObject.optString("code"), "5")) {
// Intent intent = new Intent(context, LoginActivity.class);
// intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// context.startActivity(intent);
// EnterCheckUtil.getInstance().outLogin();
// return;
// }
} catch (JSONException e) {
e.printStackTrace();
}
mHandler.post(new Runnable() {
@Override
public void run() {
okHttpCallback.onSuccess(str);
}
});
}
});
return true;
}
/**
* 同步POST
*
* @param url
* @param map
* @param okHttpCallback
* @return
*/
public boolean doSynchronizationPost(String url, Map<String, String> map, final OkHttpCallback okHttpCallback) {
if (TextUtils.isEmpty(url) || okHttpCallback == null)
return false;
//添加表单数据
FormBody.Builder formBuilder = new FormBody.Builder();
if (map != null) {
for (Map.Entry<String, String> entry : map.entrySet()) {
formBuilder.add(entry.getKey(), entry.getValue());
}
}
RequestBody requestBody = formBuilder.build();
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
Call call = client.newCall(request);
try {
Response response = call.execute();
if (response.code()!=200){
mHandler.post(new Runnable() {
@Override
public void run() {
okHttpCallback.onFailure(call.toString());
}
});
}else {
final String str = response.body().string();
try {
JSONObject jsonObject = new JSONObject(str);
// if (TextUtils.equals(jsonObject.optString("code"), "5")) {
// Intent intent = new Intent(context, LoginActivity.class);
// intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// context.startActivity(intent);
// EnterCheckUtil.getInstance().outLogin();
// return;
// }
} catch (JSONException e) {
e.printStackTrace();
}
mHandler.post(new Runnable() {
@Override
public void run() {
okHttpCallback.onSuccess(str);
}
});
}
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
/**
* 异步POST
*
* @param url
* @param map
* @param okHttpCallback
* @return
*/
public boolean doAsyncPost(String url, Map<String, String> map, final OkHttpCallback okHttpCallback) {
if (TextUtils.isEmpty(url) || okHttpCallback == null)
return false;
//添加表单数据
FormBody.Builder formBuilder = new FormBody.Builder();
if (map != null) {
for (Map.Entry<String, String> entry : map.entrySet()) {
formBuilder.add(entry.getKey(), entry.getValue());
}
}
RequestBody requestBody = formBuilder.build();
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(final Call call, IOException e) {
mHandler.post(new Runnable() {
@Override
public void run() {
okHttpCallback.onFailure(call.toString());
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String str = response.body().string();
try {
JSONObject jsonObject = new JSONObject(str);
// if (TextUtils.equals(jsonObject.optString("code"), "5")) {
// Intent intent = new Intent(context, LoginActivity.class);
// intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// context.startActivity(intent);
// EnterCheckUtil.getInstance().outLogin();
// return;
// }
} catch (JSONException e) {
e.printStackTrace();
}
mHandler.post(new Runnable() {
@Override
public void run() {
okHttpCallback.onSuccess(str);
}
});
}
});
return true;
}
/**
* 异步POST
*
* @param url
* @param param
* @param okHttpCallback
* @return
*/
public boolean doAsyncPost2(String url, String param, final OkHttpCallback okHttpCallback) {
if (TextUtils.isEmpty(url) || okHttpCallback == null)
return false;
Request request = new Request.Builder()
.url(url)
.post(RequestBody.create(MEDIA_TYPE_MARKDOWN, param))
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(final Call call, IOException e) {
mHandler.post(new Runnable() {
@Override
public void run() {
okHttpCallback.onFailure(call.toString());
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String str = response.body().string();
mHandler.post(new Runnable() {
@Override
public void run() {
okHttpCallback.onSuccess(str);
}
});
}
});
return true;
}
/**
* 上传单个文件
*
* @param url
* @param file
* @param okHttpCallback
* @return
*/
public boolean doAsyncUpload(String url, File file, final OkHttpCallback okHttpCallback) {
if (TextUtils.isEmpty(url) || file == null || okHttpCallback == null)
return false;
Request request = new Request.Builder()
.url(url)
.post(RequestBody.create(MEDIA_TYPE_MARKDOWN, file))
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(final Call call, IOException e) {
mHandler.post(new Runnable() {
@Override
public void run() {
okHttpCallback.onFailure(call.toString());
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String str = response.body().string();
mHandler.post(new Runnable() {
@Override
public void run() {
okHttpCallback.onSuccess(str);
}
});
}
});
return true;
}
/**
* 上传多个form表单数据和单张图片文件(图片参数名:pic)
*
* @param url
* @param map
* @param file
* @param okHttpCallback
* @return
*/
public boolean doAsyncMultiUpload(String url, Map<String, String> map, File file, final OkHttpCallback okHttpCallback) {
if (TextUtils.isEmpty(url) || okHttpCallback == null)
return false;
//添加表单数据
MultipartBody.Builder formBuilder = new MultipartBody.Builder();
formBuilder.setType(MultipartBody.FORM);
if (map != null) {
for (Map.Entry<String, String> entry : map.entrySet()) {
formBuilder.addFormDataPart(entry.getKey(), entry.getValue());
}
}
if (file != null) {
formBuilder.addFormDataPart("headpic", file.getAbsolutePath(), RequestBody.create(MEDIA_TYPE_PNG, file));
}
RequestBody requestBody = formBuilder.build();
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(final Call call, IOException e) {
mHandler.post(new Runnable() {
@Override
public void run() {
okHttpCallback.onFailure(call.toString());
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String str = response.body().string();
mHandler.post(new Runnable() {
@Override
public void run() {
okHttpCallback.onSuccess(str);
}
});
}
});
return true;
}
/**
* 上传多个form表单数据和图片文件(图片参数名:pic[])
*
* @param url
* @param map
* @param list
* @param okHttpCallback
* @return
*/
public boolean doAsyncMultiUpload2(String url, Map<String, String> map, List<File> list, String strIsFile, final OkHttpCallback okHttpCallback) {
if (TextUtils.isEmpty(url) || list == null || okHttpCallback == null)
return false;
//添加表单数据
MultipartBody.Builder formBuilder = new MultipartBody.Builder();
formBuilder.setType(MultipartBody.FORM);
if (map != null) {
for (Map.Entry<String, String> entry : map.entrySet()) {
formBuilder.addFormDataPart(entry.getKey(), entry.getValue());
}
}
int fileSize = list.size();
if (strIsFile.equals("1")) {
if (fileSize > 0) {
for (int i = 0; i < fileSize; i++) {
formBuilder.addFormDataPart("pic[]", list.get(i).getAbsolutePath(), RequestBody.create(MEDIA_TYPE_PNG, list.get(i)));
}
}
} else {
if (fileSize > 0) {
for (int i = 0; i < fileSize; i++) {
formBuilder.addFormDataPart("video", list.get(i).getAbsolutePath(), RequestBody.create(MediaType.parse("video/mp4"), list.get(i)));
}
}
}
RequestBody requestBody = formBuilder.build();
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(final Call call, IOException e) {
mHandler.post(new Runnable() {
@Override
public void run() {
okHttpCallback.onFailure(call.toString());
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String str = response.body().string();
mHandler.post(new Runnable() {
@Override
public void run() {
okHttpCallback.onSuccess(str);
}
});
}
});
return true;
}
/**
* 上传多个form表单数据和图片文件(图片参数名:thumb)附件files
*
* @param url
* @param map
* @param list
* @param okHttpCallback
* @return
*/
public boolean doAsyncMultiUpload3(String url, Map<String, String> map, File mFile, List<File> list, String strIsFile, final OkHttpCallback okHttpCallback) {
if (TextUtils.isEmpty(url) || list == null || okHttpCallback == null)
return false;
//添加表单数据
MultipartBody.Builder formBuilder = new MultipartBody.Builder();
formBuilder.setType(MultipartBody.FORM);
if (map != null) {
for (Map.Entry<String, String> entry : map.entrySet()) {
formBuilder.addFormDataPart(entry.getKey(), entry.getValue());
}
}
int fileSize = list.size();
if (strIsFile.equals("1")) {
if (fileSize > 0) {
for (int i = 0; i < fileSize; i++) {
formBuilder.addFormDataPart("thumb[]", list.get(i).getAbsolutePath(), RequestBody.create(MEDIA_TYPE_PNG, list.get(i)));
}
}
} else {
if (fileSize > 0) {
for (int i = 0; i < fileSize; i++) {
formBuilder.addFormDataPart("video", list.get(i).getAbsolutePath(), RequestBody.create(MediaType.parse("video/mp4"), list.get(i)));
}
}
}
if (mFile != null) {
formBuilder.addFormDataPart("files", mFile.getAbsolutePath(), RequestBody.create(MediaType.parse("text/plain"), mFile));
}
RequestBody requestBody = formBuilder.build();
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(final Call call, IOException e) {
mHandler.post(new Runnable() {
@Override
public void run() {
okHttpCallback.onFailure(call.toString());
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String str = response.body().string();
mHandler.post(new Runnable() {
@Override
public void run() {
okHttpCallback.onSuccess(str);
}
});
}
});
return true;
}
/**
* 上传多个form表单数据和图片文件(图片参数名:thumb)附件files
*
* @param url
* @param map
* @param list
* @param okHttpCallback
* @return
*/
public boolean doAsyncMultiUpload4(String url, Map<String, String> map, File mFileVideo, File mFileVideoImage, List<File> list, String strIsFile, final OkHttpCallback okHttpCallback) {
if (TextUtils.isEmpty(url) || list == null || okHttpCallback == null)
return false;
//添加表单数据
MultipartBody.Builder formBuilder = new MultipartBody.Builder();
formBuilder.setType(MultipartBody.FORM);
if (map != null) {
for (Map.Entry<String, String> entry : map.entrySet()) {
formBuilder.addFormDataPart(entry.getKey(), entry.getValue());
}
}
int fileSize = list.size();
if (strIsFile.equals("1")) {
if (fileSize > 0) {
for (int i = 0; i < fileSize; i++) {
formBuilder.addFormDataPart("pic[]", list.get(i).getAbsolutePath(), RequestBody.create(MEDIA_TYPE_PNG, list.get(i)));
}
}
} else {
if (fileSize > 0) {
for (int i = 0; i < fileSize; i++) {
formBuilder.addFormDataPart("video", list.get(i).getAbsolutePath(), RequestBody.create(MediaType.parse("video/mp4"), list.get(i)));
}
}
}
if (mFileVideo != null) {
formBuilder.addFormDataPart("video_url", mFileVideo.getAbsolutePath(), RequestBody.create(MediaType.parse("text/plain"), mFileVideo));
}
if (mFileVideoImage != null) {
formBuilder.addFormDataPart("video_img", mFileVideoImage.getAbsolutePath(), RequestBody.create(MediaType.parse("text/plain"), mFileVideoImage));
}
RequestBody requestBody = formBuilder.build();
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(final Call call, IOException e) {
mHandler.post(new Runnable() {
@Override
public void run() {
okHttpCallback.onFailure(call.toString());
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String str = response.body().string();
mHandler.post(new Runnable() {
@Override
public void run() {
okHttpCallback.onSuccess(str);
}
});
}
});
return true;
}
/**
* 上传多个form表单数据和图片文件(图片参数名:自定义)
*
* @param url
* @param map
* @param list
* @param okHttpCallback
* @return
*/
public boolean doAsyncMultiUpload(String url, Map<String, String> map, List<File> list, String paramName, final OkHttpCallback okHttpCallback) {
if (TextUtils.isEmpty(url) || list == null || okHttpCallback == null)
return false;
//添加表单数据
MultipartBody.Builder formBuilder = new MultipartBody.Builder();
formBuilder.setType(MultipartBody.FORM);
if (map != null) {
for (Map.Entry<String, String> entry : map.entrySet()) {
formBuilder.addFormDataPart(entry.getKey(), entry.getValue());
}
}
int fileSize = list.size();
if (fileSize > 0) {
for (int i = 0; i < fileSize; i++) {
formBuilder.addFormDataPart(paramName, list.get(i).getAbsolutePath(), RequestBody.create(MEDIA_TYPE_PNG, list.get(i)));
}
}
RequestBody requestBody = formBuilder.build();
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(final Call call, IOException e) {
mHandler.post(new Runnable() {
@Override
public void run() {
okHttpCallback.onFailure(call.toString());
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String str = response.body().string();
mHandler.post(new Runnable() {
@Override
public void run() {
okHttpCallback.onSuccess(str);
}
});
}
});
return true;
}
public boolean doAsyncMultiUpload223(String url, Map<String, String> map, File mFileVideo, File mFileVideoImage, List<File> list, String paramName, final OkHttpCallback okHttpCallback) {
if (TextUtils.isEmpty(url) || list == null || okHttpCallback == null)
return false;
//添加表单数据
MultipartBody.Builder formBuilder = new MultipartBody.Builder();
formBuilder.setType(MultipartBody.FORM);
if (map != null) {
for (Map.Entry<String, String> entry : map.entrySet()) {
formBuilder.addFormDataPart(entry.getKey(), entry.getValue());
}
}
int fileSize = list.size();
if (fileSize > 0) {
for (int i = 0; i < fileSize; i++) {
formBuilder.addFormDataPart(paramName, list.get(i).getAbsolutePath(), RequestBody.create(MEDIA_TYPE_PNG, list.get(i)));
}
}
if (mFileVideo != null) {
formBuilder.addFormDataPart("videourl", mFileVideo.getAbsolutePath(), RequestBody.create(MediaType.parse("text/plain"), mFileVideo));
}
if (mFileVideoImage != null) {
formBuilder.addFormDataPart("videoimg", mFileVideoImage.getAbsolutePath(), RequestBody.create(MediaType.parse("text/plain"), mFileVideoImage));
}
RequestBody requestBody = formBuilder.build();
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(final Call call, IOException e) {
mHandler.post(new Runnable() {
@Override
public void run() {
okHttpCallback.onFailure(call.toString());
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String str = response.body().string();
mHandler.post(new Runnable() {
@Override
public void run() {
okHttpCallback.onSuccess(str);
}
});
}
});
return true;
}
public boolean doAsyncMultiUpload443(String url, Map<String, String> map, File mFileVideo, File mFileFujian, File mFileVideoImage, List<File> list, String paramName, final OkHttpCallback okHttpCallback) {
if (TextUtils.isEmpty(url) || list == null || okHttpCallback == null)
return false;
//添加表单数据
MultipartBody.Builder formBuilder = new MultipartBody.Builder();
formBuilder.setType(MultipartBody.FORM);
if (map != null) {
for (Map.Entry<String, String> entry : map.entrySet()) {
formBuilder.addFormDataPart(entry.getKey(), entry.getValue());
}
}
int fileSize = list.size();
if (fileSize > 0) {
for (int i = 0; i < fileSize; i++) {
formBuilder.addFormDataPart(paramName, list.get(i).getAbsolutePath(), RequestBody.create(MEDIA_TYPE_PNG, list.get(i)));
}
}
if (mFileVideo != null) {
formBuilder.addFormDataPart("videourl", mFileVideo.getAbsolutePath(), RequestBody.create(MediaType.parse("text/plain"), mFileVideo));
}
if (mFileVideoImage != null) {
formBuilder.addFormDataPart("videoimg", mFileVideoImage.getAbsolutePath(), RequestBody.create(MediaType.parse("text/plain"), mFileVideoImage));
}
if (mFileFujian != null) {
formBuilder.addFormDataPart("appendix", mFileFujian.getAbsolutePath(), RequestBody.create(MediaType.parse("text/plain"), mFileFujian));
}
RequestBody requestBody = formBuilder.build();
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(final Call call, IOException e) {
mHandler.post(new Runnable() {
@Override
public void run() {
okHttpCallback.onFailure(call.toString());
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String str = response.body().string();
mHandler.post(new Runnable() {
@Override
public void run() {
okHttpCallback.onSuccess(str);
}
});
}
});
return true;
}
public boolean doAsyncMultiUpload(String url, String name, List<File> videoList, List<File> picList, final OkHttpCallback okHttpCallback) {
if (TextUtils.isEmpty(url) || videoList == null || picList == null || okHttpCallback == null)
return false;
//添加表单数据
MultipartBody.Builder formBuilder = new MultipartBody.Builder();
formBuilder.setType(MultipartBody.FORM);
int fileSize = videoList.size();
for (int i = 0; i < fileSize; i++) {
formBuilder.addFormDataPart(name, videoList.get(i).getAbsolutePath(), RequestBody.create(MediaType.parse("video/mp4"), videoList.get(i)));
}
int fileSize2 = picList.size();
for (int i = 0; i < fileSize2; i++) {
formBuilder.addFormDataPart(name, picList.get(i).getAbsolutePath(), RequestBody.create(MEDIA_TYPE_PNG, picList.get(i)));
}
RequestBody requestBody = formBuilder.build();
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(final Call call, IOException e) {
mHandler.post(new Runnable() {
@Override
public void run() {
okHttpCallback.onFailure(call.toString());
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String str = response.body().string();
mHandler.post(new Runnable() {
@Override
public void run() {
okHttpCallback.onSuccess(str);
}
});
}
});
return true;
}
/**
* 异步GET
* 广告统计专用,定制user_agent
* httpclient 会重复请求
*
* @param url
* @param okHttpCallback
* @return
*/
public boolean doAsyncStatsGet(String url, final OkHttpCallback okHttpCallback) {
if (TextUtils.isEmpty(url) || okHttpCallback == null) {
return false;
}
Request.Builder builder = new Request.Builder().url(url);
builder.method("GET", null);
Request request = builder.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(final Call call, IOException e) {
mHandler.post(new Runnable() {
@Override
public void run() {
okHttpCallback.onFailure(call.toString());
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String str = response.body().string();
mHandler.post(new Runnable() {
@Override
public void run() {
okHttpCallback.onSuccess(str);
}
});
}
});
return true;
}
/**
* 下载文件
*
* @param fileUrl 文件url
* @param destFileDir 存储目标目录
*/
private long current = 0;
public void downLoadFile(String fileUrl, final String destFileDir, final String fileName, final OkHttpDownCallBack callBack) {
isStop = false;
current = 0;
final File file = new File(destFileDir, fileName);
if (file.exists()) {
mHandler.post(new Runnable() {
@Override
public void run() {
callBack.onDownSuccess(file);
}
});
return;
}
Request.Builder builder = new Request.Builder().url(fileUrl);
builder.method("GET", null);
Request request = builder.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
mHandler.post(new Runnable() {
@Override
public void run() {
callBack.onDownFailed("下载失败");
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
InputStream is = null;
byte[] buf = new byte[2048];
int len = 0;
FileOutputStream fos = null;
try {
final long total = response.body().contentLength();
// ULog.e("cc", "total------>" + total);
is = response.body().byteStream();
fos = new FileOutputStream(file);
while ((len = is.read(buf)) != -1) {
current += len;
fos.write(buf, 0, len);
// ULog.e("cc", "current------>" + current);
mHandler.post(new Runnable() {
@Override
public void run() {
callBack.onDownloading(total, current);
}
});
if (isStop) {
mHandler.post(new Runnable() {
@Override
public void run() {
callBack.onDownFailed("下载失败");
}
});
return;
}
}
fos.flush();
mHandler.post(new Runnable() {
@Override
public void run() {
callBack.onDownSuccess(file);
}
});
} catch (IOException e) {
// ULog.e("cc", e.toString());
mHandler.post(new Runnable() {
@Override
public void run() {
callBack.onDownFailed("下载失败");
}
});
} finally {
try {
if (is != null) {
is.close();
}
if (fos != null) {
fos.close();
}
} catch (IOException e) {
// ULog.e("cc", e.toString());
}
}
}
});
}
private boolean isStop;
public void stop() {
isStop = true;
}
}
4)、调用方式
先在Application里初始化
OkHttpUtil.getInstance().init(getApplicationContext());
然后在使用的地方调用,例:
new Thread(new Runnable() {
@Override
public void run() {
OkHttpUtil.getInstance().doSynchronizationGet(url_get_synchronization, new OkHttpCallback() {
@Override
public void onSuccess(String response) {
tv_result.setText(response);
}
@Override
public void onFailure(String errorMsg) {
tv_result.setText(errorMsg);
}
});
}
}).start();
OkhttpDemo地址为: https://github.com/qq919953719/OkhttpUtil