記錄的一些Retrofit的小用法

思考者23發表於2017-12-21

本文僅記錄一些在使用Retrofit+OkHttp+RxJava模式時所用到的一些方案,方便查詢,說明什麼的還是算了吧

自定義轉換器

提供的轉換器雖方便,可要完全按Json建model還是算了吧
  • 最直接的轉換器,回撥一個JsonObject

    public class CommonConverterFactory extends Converter.Factory {
        private RequestJsonInterface dealInterface;

        @Nullable
        @Override
        public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
            return new JsonResponseBodyConverter<>();
        }

        @Nullable
        @Override
        public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
            return super.requestBodyConverter(type, parameterAnnotations, methodAnnotations, retrofit);
        }

        public CommonConverterFactory() {

        }

        public CommonConverterFactory(RequestJsonInterface dealInterface1) {
            dealInterface = dealInterface1;
        }

        public class JsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
            @Override
            public T convert(ResponseBody value) throws IOException {
                String response = value.string();
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (dealInterface != null) {
                        return (T) dealInterface.deal(jsonObject);
                    }else {
                        return (T) new Object();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                return null;
            }
        }

    }


複製程式碼

這裡建立了一個簡單的轉換器,其中的JsonResponseBodyConverter會將ResponseBody轉換為一個JsonObject,然後可以按照自己的意思處理,自然,也可以對其進行擴充套件。

通過攔截器進行請求時的自動加密

加密是一個常見需求,以確保傳遞的正確性,多數時是通過要傳遞的引數通過一定的演算法生成一個加密值,可以通過攔截器獲取所有的引數並進行加密
//建立的一個請求工具類的初始化方法
public RequestHelper(int timeOut, final boolean isSignature, final boolean isUserID, Converter.Factory factory) {
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder()
                .connectTimeout(timeOut, TimeUnit.SECONDS)
                .writeTimeout(timeOut, TimeUnit.SECONDS)
                .readTimeout(timeOut, TimeUnit.SECONDS);
        if (!(!isKey & !isSignature)) {
            clientBuilder.addInterceptor(new Interceptor() {
                @Override public Response intercept(Chain chain) throws IOException {
                    Request request = chain.request();
                    Request.Builder requestBuilder = request.newBuilder();
                    if (request.body() instanceof FormBody) {
                        FormBody.Builder builder = new FormBody.Builder();
                        FormBody body = (FormBody)request.body();
                        Map<String, String> param = new HashMap<String, String>();
                        for (int index = 0; index < body.size(); index++) {
                            param.put(body.encodedName(index), body.encodedValue(index));
                            builder.addEncoded(body.encodedName(index), body.encodedValue(index));
                        }
                        
                        if (isKey) {
                        //此處是希望為每一個請求新增一個引數key
                            if (BaseApplication.getKey() != null) {
                                builder.add("key", BaseApplication.getKey());
                                param.put("key", BaseApplication.getKey());
                            }
                        }
                        if (isSignature) {
                        //此處為新增加簽引數signature
                            builder.add("signature", encryptParam(param));
                        }
                        requestBuilder.method(request.method(), builder.build());
                    }
                    Request newRequest = requestBuilder.build();
                    return chain.proceed(newRequest);
                }
            });
        }
        clientBuilder.addInterceptor(loggingInterceptor);
        OkHttpClient client = clientBuilder.build();
        Retrofit retrofit = new Retrofit.Builder().baseUrl(BASE_URL).client(client).addConverterFactory(factory)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create()).build();
        requestApi = retrofit.create(RequestApi.class);
    }

/**加簽函式*/
private String encryptParam(Map<String, String> param) {
    String encrypt = "";
    ***加簽過程***
    return encrypt;
}
複製程式碼

相關文章