《Android学习笔记总结+最新移动架构视频+大厂安卓面试真题+项目实战源码讲义》
完整开源地址:https://docs.qq.com/doc/DSkNLaERkbnFoS0ZF
/**
* 设置请求超时
*/
private static void initOkHttpClient() {
File sdcache = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/cache");
int cacheSize = 10 * 1024 * 1024;
OkHttpClient.Builder builder = new OkHttpClient.Builder()
.connectTimeout(15, TimeUnit.SECONDS)
.writeTimeout(20, TimeUnit.SECONDS)
.readTimeout(20, TimeUnit.SECONDS)
.cache(new Cache(sdcache.getAbsoluteFile(), cacheSize));
mOkHttpClient = builder.build();
}
/**
* get异步请求
*/
public void getAsynHttp(final int what, final HttpCallBack httpCallBack, final String httpUrl) {
Request.Builder requestBuilder = new Request.Builder().url(httpUrl);
requestBuilder.method("GET", null);
Request request = requestBuilder.build();
Call mcall = mOkHttpClient.newCall(request);
mcall.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
httpCallBack.onFailure(what, e.toString());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
httpCallBack.onResponse(what, response.body().string());
}
});
}
/**
* post异步请求
*/
public void postAsynHttp(final int what, final HttpCallBack httpCallBack, final String httpUrl, final Map<String, String> stringMap) {
FormBody.Builder formBody = new FormBody.Builder();
for (String key : stringMap.keySet()) {
formBody.add(key, stringMap.get(key));
}
Request request = new Request.Builder()
.url(httpUrl)
.post(formBody.build())
.build();
Call call = mOkHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
httpCallBack.onFailure(what, e.toString());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
httpCallBack.onResponse(what, response.body().string());
}
});
}
/**
* 异步下载文件
*/
public void downAsynFile(final int what, final HttpCallBack httpCallBack, final String httpFilePath, final String filePath) {
Request request = new Request.Builder().url(httpFilePath).build();
mOkHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
httpCallBack.onFailure(what, e.toString());
}
@Override
public void onResponse(Call call, Response response) {
InputStream inputStream = response.body().byteStream();
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(new File(filePath));
byte[] buffer = new byte[5 * 1024 * 1024];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, len);
}
fileOutputStream.flush();
httpCallBack.onResponse(what, "下载成功");
} catch (IOException e) {
e.printStackTrace();
httpCallBack.onResponse(what, "下载异常:" + e.toString());
}
}
});
}
public interface HttpCallBack {
/**
* 访问成功回调接口
*/
void onResponse(int what, String response);
/**
* 访问成错误回调接口