使用場(chǎng)景:
甲方粑粑不積德呐馆,找外包公司給他們開發(fā)的時(shí)候,運(yùn)氣不好分配到實(shí)習(xí)生給你寫SDK莲兢。然后可怕的就來了汹来,這個(gè)SDK流落到你手上,讓你來開發(fā)應(yīng)用改艇。
這就非常尷尬了收班。
該sdk讓你這樣用
BasicSdk sdk = new BasicSdk();
sdk.login(username,psw);
sdk.setOnlogin(new logincallback(){
onLogin(LoginResult result){
}
});
我當(dāng)時(shí)就驚呆了,都0202年了谒兄,還有這種sdk嗎闺阱。
但其實(shí)我們還是可以反抗一下的。用OkHttp的Interceptor舵变。
比如說,參考他們sdk內(nèi)部的實(shí)現(xiàn)酣溃,來實(shí)現(xiàn)我們的Interceptor邏輯
請(qǐng)求體的Interceptor
public class UserInterceptor implements Interceptor {
@NonNull
@Override
public Response intercept(@NonNull Chain chain) throws IOException{
Request request = chain.request();
Request.Builder builder = request.newBuilder();
//增加header,沒問題
builder.addHeader("requestId", requestId)
.addHeader("token",token);
RequestBody body = request.body();
if (body instanceof FormBody) {
// 將參數(shù)組裝成json格式
FormBody formBody = (FormBody) body;
JsonObject json = new JsonObject();
int size = formBody.size();
String name;
String value;
for (int i = 0; i < size; i++) {
// 有些服務(wù)器不識(shí)別轉(zhuǎn)碼之后的字符串
name = formBody.name(i);
value = formBody.value(i);
json.addProperty(name, value);
}
RequestBody newBody = RequestBody.create(JSON, json.toString());
builder.method("POST", newBody);
}
//把請(qǐng)求體纪隙,重新構(gòu)建成自己想要的樣子赊豌,并返回
return chain.proceed(builder.build());
}
}
返回體的Interceptor
public class ResponseInterceptor implements Interceptor {
@NonNull
@Override
public Response intercept(@NonNull Chain chain) throws IOException {
Request request = chain.request();
Response response = chain.proceed(request);
ResponseBody responseBody = response.body();
if (responseBody != null) {
String responseString = responseBody.string();
...實(shí)現(xiàn)自己的解析
ResponseBody newBody;
//也可以throw一個(gè)Exception讓后面的處理
throw new CustomException()
....
//把解析后重新拼接的內(nèi)容放newBody然后返回
return response.newBuilder()
.body(newBody)
.build();
}
結(jié)合retrofit使用
public class UserService extends BaseHttpsService{
// 保證只初始化一次,避免資源浪費(fèi)
private static volatile UserService userService;
private UserApi api; //retrofit注解的接口
public UserApi getApi() {
return api;
}
private void initApi() {
Gson gson = new GsonBuilder()
.create();
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
//添加了請(qǐng)求體和返回體的攔截器
OkHttpClient httpClient =builder
.addInterceptor(AccountInterceptor.newInstance())
.addInterceptor(ResponseInterceptor.newInstance())
.addInterceptor(loggingInterceptor)
.build();
//構(gòu)建retrofit對(duì)象
Retrofit retrofit = new Retrofit.Builder()
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create(gson))
.baseUrl(ServerConfig.URL) //也可以這樣指定baseUrl
.client(httpClient)
.build();
api = retrofit.create(UserApi .class);
}
}
配置https的基類BaseHttpsService
public class BaseHttpsService {
protected OkHttpClient.Builder builder;
protected BaseHttpsService(){
X509TrustManager xtm = new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
};
SSLContext sslContext;
try {
sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, new TrustManager[]{xtm}, new SecureRandom());
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
SSLSocketFactory sslSocketFactory = new SSLSocketFactoryCompat(xtm);
HostnameVerifier DO_NOT_VERIFY = (hostname, session) -> true;
builder = new OkHttpClient.Builder()
.writeTimeout(10, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS)
.sslSocketFactory(sslSocketFactory, xtm)
.hostnameVerifier(DO_NOT_VERIFY);
}
}