OkHttp3开发三部曲:
1、创建OkHttpClient,添加配置
2、创建请求
3、执行请求
下面分别来说说这三个步骤:
一、创建OkHttpClient
一个最简单的OkHttpClient
OkHttpClient okHttpClient=new OkHttpClient.Builder().build();
一个复杂点的OkHttpClient配置
File cacheDir = new File(getCacheDir(), "okhttp_cache");
//File cacheDir = new File(getExternalCacheDir(), "okhttp");
Cache cache = new Cache(cacheDir, 10 * 1024 * 1024);
okHttpClient = new OkHttpClient.Builder()
.connectTimeout(5*1000, TimeUnit.MILLISECONDS) //链接超时
.readTimeout(10*1000,TimeUnit.MILLISECONDS) //读取超时
.writeTimeout(10*1000,TimeUnit.MILLISECONDS) //写入超时
.addInterceptor(new HttpHeadInterceptor()) //应用拦截器:统一添加消息头
.addNetworkInterceptor(new NetworkspaceInterceptor())//网络拦截器
.addInterceptor(loggingInterceptor)//应用拦截器:打印日志
.cache(cache) //设置缓存
.build();
具体可配置参数见OkHttpClient.Builder类,几点注意事项:
1、拦截器
两种拦截器:Interceptor(应用拦截器)、NetworkInterceptor(网络拦截器)
1)Interceptor比NetworkInterceptor先执行
2)同一种Interceptor倒序返回
A(start)----B(start)----B(end)----A(end)
因此上面配置的Interceptor执行顺序如下
HttpHeadInterceptor start----LoggingInterceptor start----LoggingInterceptor end---HttpHeadInterceptor end
3)日志拦截器
自定义日志拦截器
public class LoggingInterceptor implements Interceptor {
private static final String TAG="Okhttp";
@Override public Response intercept(Interceptor.Chain chain) throws IOException {
Request request = chain.request();
long t1 = System.nanoTime();
Log.d(TAG,String.format("Sending request %s on %s%n%s",
request.url(), chain.connection(), request.headers()));
Response response = chain.proceed(request);
long t2 = System.nanoTime();
Log.d(TAG,String.format("Received response for %s in %.1fms%n%s",
response.request().url(), (t2 - t1) / 1e6d, response.headers()));
MediaType mediaType = response.body().contentType();
String content = response.body().string();
Log.d(TAG,content);
response=response.newBuilder()
.body(ResponseBody.create(mediaType,content))
.build();
return response;
}
}
官方提供的Logging Interceptor
地址:https://github.com/victorfan336/okhttp-logging-interceptor
gradle.build中添加依赖:
compile 'com.squareup.okhttp3:logging-interceptor:3.1.2'
使用
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(Level.BODY);//日志级别,Body级别打印的信息最全面
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(logging)
.build();
2、开发中应该只维护一个OkHttpClient实例,这样可以复用连接池、线程池等,避免性能开销
如果想修改参数,可通过
okHttpClient.newBuilder()修改,这样可以复用okHttpClient之前的所有配置,
比如想针对某个请求修改链接超时。
OkHttpClient newClient=okHttpClient.newBuilder()
.connectTimeout(10*1000,TimeUnit.MILLISECONDS)
.build();
newClient.newCall(req);
二、创建请求
通过Request.Builder创建请求,默认是Get请求
Request req = new Request.Builder().url(url).build();
Call call=okHttpClient.newCall(req);
GET请求
Request req = new Request.Builder().url(url).build();
okHttpClient.newCall(req);
POST请求
主要是构建RequestBody,并设置Content-Type消息头。
1、普通Post请求比如json请求
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), jsonObject.toString());
Request req = new Request.Builder().url(url)
.post(requestBody)
.build();
okHttpClient.newCall(req);
2、表单POST请求
Content-Type: application/x-www-form-urlencoded
比如:
RequestBody requestBody =
new FormBody.Builder()
.add("username", "zhangsan")
.add("password", "1111111")
.build();
Request req = new Request.Builder().url(url).post(uploadBody).build();
okHttpClient.newCall(req);
3、表单上传文件
Content-Type: multipart/form-data
比如:
RequestBody uploadImg = RequestBody.create(MediaType.parse("image/jpeg"), file);
MultipartBody uploadBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("username", "zhangsan")
.addFormDataPart("password", "11111")
.addFormDataPart("img", fileName, uploadImg)
.build();
Request req = new Request.Builder().url(url).post(uploadBody).build();
okHttpClient.newCall(req);
三、执行请求
1、同步执行
Response response = call.execute();
由于android强制要求网络请求在线程中执行,所以无法使用execute
2、异步执行
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
//失败回调
}
@Override
public void onResponse(Call call, Response response) throws IOException {
//成功回调,当前线程为子线程,如果需要更新UI,需要post到主线程中
boolean successful = response.isSuccessful();
//响应消息头
Headers headers = response.headers();
//响应消息体
ResponseBody body = response.body();
String content=response.body().string());
//缓存控制
CacheControl cacheControl = response.cacheControl();
}
});
1)Response:封装了网络响应消息,比如响应消息头、缓存控制、响应消息体等。
String content=response.body().string(); //获取字符串
InputStream inputStream = response.body().byteStream();//获取字节流(比如下载文件)
2)Callback回调是在子线程中执行的,如果要更新UI,请post到主线程中。
Okhttp使用上的一些缺点
1、对于Get请求,如果请求参数较多,自己拼接Url较为麻烦
比如
HttpUrl httpUrl = new HttpUrl.Builder()
.scheme("http")
.host("www.baidu.com")
.addPathSegment("user")
.addPathSegment("login")
.addQueryParameter("username", "zhangsan")
.addQueryParameter("password","123456")
.build();
拼接结果:http://www.baidu.com/user/login/username=zhangsan&password=123456
如果能做一些封装,直接addParam(key,value)的形式则会简单很多。
2、Callback在子线程中回调,大部分时候,我们都是需要更新UI的,还需自己post到主线程中处理。
3、构建请求步骤比较多
因此,Square提供了针对OkHttp的封装库Retrofit,另外Github上也有很多第三方的封装库,比如OkGo。
参考文档
https://github.com/square/okhttp/wiki
https://github.com/victorfan336/okhttp-logging-interceptor
http://www.jianshu.com/p/2710ed1e6b48