使用OkHttp Interceptor應(yīng)對(duì)甲方糟糕的SDK

使用場(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);
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容