OkHttp 源码解读 HTTP
发布于: 21 小时前
1.项目概要:
本文主要介绍OkHttp如何使用,源码解读,如何实现HTTP请求?
复制代码
2.背景和需求
OkHttp 是一个执行效率比较高的 Http 客户端:
支持 HTTP/2 ,当多个请求对应同一 host 地址时,可共用同一个 socket;
连接池可减少请求延迟(如果 HTTP/2 不可用);
支持 GZIP 压缩,减少网络传输的数据大小;
支持 Response 数据缓存,避免重复网络请求;
3.实现原理
package com.security.weichat.retrofit;
import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.security.weichat.AppConfig;
import com.security.weichat.BuildConfig;
import com.security.weichat.util.RxBus;
import com.security.weichat.volley.Result;
import java.io.IOException;
import java.io.Reader;
import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;
import java.util.concurrent.TimeUnit;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.internal.platform.Platform;
import okhttp3.logging.HttpLoggingInterceptor;
import okio.Buffer;
import okio.BufferedSource;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import static com.alibaba.fastjson.util.IOUtils.UTF8;
import static com.alibaba.fastjson.util.IOUtils.stringSize;
import static com.security.weichat.activity.live.LiveListenerService.EXTRA_DELETE_USER;
import static com.security.weichat.activity.live.LiveListenerService.SOCKET_DELETE_USER_EVENT;
import static okhttp3.internal.platform.Platform.INFO;
/**
* Created by Rabbpig on 2017/7/27.
*/
public class IMSearchUserApi {
private IMSearchUserService mIMSearchUserService;
private Gson mGson;
IMSearchUserApi(){
mGson = new GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
.serializeNulls()
.create();
OkHttpClient.Builder builder = new OkHttpClient.Builder();
if (BuildConfig.DEBUG) {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
builder.addInterceptor(interceptor);
}
// builder.addInterceptor(mInterceptor);
builder.retryOnConnectionFailure(true)
.connectTimeout(15, TimeUnit.SECONDS)
.readTimeout(15,TimeUnit.SECONDS);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(AppConfig.getInstance().getServerConfig().getBaseUrl())
.client(builder.build())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create(mGson))
// .addConverterFactory(FastJsonConverterFactory.create())
.build();
mIMSearchUserService = retrofit.create(IMSearchUserService.class);
Platform.get().log(INFO, "这是IMSearchUserApi构造方法!!", null);
}
public IMSearchUserService getIMSearchUserService() {
return mIMSearchUserService;
}
private Interceptor mInterceptor = new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Platform logger = Platform.get();
logger.log(INFO, "自定义拦截器!!", null);
Request request = chain.request();
Response response = chain.proceed(request);
// Reader reader = response.body().charStream();
// logger.log(INFO, "拦截器:"+response.toString(), null);
ResponseBody responseBody = response.body();
BufferedSource source = responseBody.source();
source.request(Long.MAX_VALUE); // Buffer the entire body.
Buffer buffer = source.buffer();
Charset charset = UTF8;
MediaType contentType = responseBody.contentType();
if (contentType != null) {
try {
charset = contentType.charset(UTF8);
} catch (UnsupportedCharsetException e) {
logger.log(INFO, "Couldn't decode the response body; charset is likely malformed.", null);
return response;
}
}
String result = buffer.clone().readString(charset);
Platform.get().log(INFO, "请求结果:"+result, null);
Result resultObj = mGson.fromJson(result, Result.class);
logger.log(INFO, "转换结果 getResultCode = "+resultObj.getResultCode(), null);
if (null != resultObj && resultObj.getResultCode() == 1030102){
logger.log(INFO, "自定义拦截器 token 过期,调用 RxBus.getDefault().send(resultObj)", null);
RxBus.getDefault().send(resultObj);
logger.log(INFO, "自定义拦截器 token 过期,需要重新登陆", null);
}
return response;
}
};
复制代码
4.使用方法
5.对比
6.成果展示
7.参考文献
划线
评论
复制
发布于: 21 小时前阅读数: 7
版权声明: 本文为 InfoQ 作者【Changing Lin】的原创文章。
原文链接:【http://xie.infoq.cn/article/0bc1e92554b53bb6bc10f7fbe】。文章转载请联系作者。
Changing Lin
关注
获得机遇的手段远超于固有常规之上~ 2020.04.29 加入
我能做的,就是调整好自己的精神状态,以最佳的面貌去面对那些未曾经历过得事情,对生活充满热情和希望。
评论