Retrofit2自定義攔截器和ConverterFactory實現客戶端與服務端加密通信

網絡請求框架使用的retrofit,客戶端與服務端之間需要加密通信并且請求需要gzip壓縮。為完成這一需求,需要攔截請求和響應。特此記錄下修改請求的過程,希望可以幫助有需要的人。

處理request

retrofit2使用okhttp3.x,請求上的處理只需要給okhttp添加攔截器即可

這里與服務端通信相互之間對稱加密,并且需要開啟gzip壓縮,因此這里定義了三個攔截器完成這一需求

  1. 修改請求頭

     public class RequestHeaderInterceptor implements Interceptor {
         @Override
         public Response intercept(Chain chain) throws IOException {
             Request originalRequest = chain.request();
             Request updateRequest = originalRequest.newBuilder()
                     .header("Content-Type", "text/plain; charset=utf-8")
                     .header("Accept", "*/*")
                     .header("Accept-Encoding", "gzip")
                     .build();
             return chain.proceed(updateRequest);
         }
     }
    
  2. 加密請求內容

     public class RequestEncryptInterceptor implements Interceptor {
         @Override
         public Response intercept(Chain chain) throws IOException {
             Request request = chain.request();
             RequestBody body = request.body();
             Buffer buffer = new Buffer();
             body.writeTo(buffer);
             Charset charset = Charset.forName("UTF-8");
             MediaType contentType = body.contentType();
             if (contentType != null) {
                 charset = contentType.charset(charset);
             }
             String paramsStr = buffer.readString(charset);
             try {
                 paramsStr = EncryptUtils.encryptParams(paramsStr);
             } catch (Exception e) {
                 LogUtils.e(e);
             }
             RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain; charset=utf-8"), paramsStr);
             request = request.newBuilder()
                     .post(requestBody)
                     .build();
             return chain.proceed(request);
         }
     }
    
  3. 啟用Gzip壓縮

     public class GzipRequsetInterceptor implements Interceptor {
         @Override
         public Response intercept(Chain chain) throws IOException {
             Request originalRequest = chain.request();
             if (originalRequest.body() == null || originalRequest.header("Content-Encoding") != null) {
                 return chain.proceed(originalRequest);
             }
             Request compressedRequest = originalRequest.newBuilder()
                     .header("Content-Encoding", "gzip")
                     .method(originalRequest.method(), gzip(originalRequest.body()))
                     .build();
             return chain.proceed(compressedRequest);
         }
     
         private RequestBody gzip(final RequestBody body) {
             return new RequestBody() {
                 @Override
                 public MediaType contentType() {
                     return body.contentType();
                 }
     
                 @Override
                 public long contentLength() throws IOException {
                     return -1;
                 }
     
                 @Override
                 public void writeTo(BufferedSink sink) throws IOException {
                     BufferedSink gzipSink = Okio.buffer(new GzipSink(sink));
                     body.writeTo(gzipSink);
                     gzipSink.close();
                 }
             };
         }
     }
    

處理response

對response處理需要未retrofit設置自定義的ConverterFactory,因客戶端與服務端使用json通信,因此我們參考官方提供GsonConverterFactory編寫

自定義GsonConverterFactory,其實相對于原版只修改了responseBodyConverter方法的內容,requestBodyConverter依舊用的原版內容。

注意,GsonRequestBodyConverter類的修飾符不是public,需要將其代碼拷貝出來

public final class CustomGsonConverterFactory extends Converter.Factory {

    private final Gson gson;

    public static CustomGsonConverterFactory create() {
        return create(new Gson());
    }

    @SuppressWarnings("ConstantConditions") // Guarding public API nullability.
    public static CustomGsonConverterFactory create(Gson gson) {
        if (gson == null) throw new NullPointerException("gson == null");
        return new CustomGsonConverterFactory(gson);
    }
   
    private CustomGsonConverterFactory(Gson gson) {
        this.gson = gson;
    }

    @Override
    public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
        TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type));
        return new CustomGsonResponseConverter<>(gson, adapter);
    }

    @Override
    public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
        TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type));
        return new GsonRequestBodyConverter<>(gson, adapter);
    }

}

修改GsonResponseConverter,使其解密后再處理內容。

注意:這里預處理json的過程并非通用步驟,因我的json格式是 { "code": 0, "message": "success", "data": { ... } }這樣的,如果你的不同請換一種方式。

class CustomGsonResponseConverter<T> implements Converter<ResponseBody, T> {

    private final Gson gson;
    private final TypeAdapter<T> adapter;

    CustomGsonResponseConverter(Gson gson, TypeAdapter<T> adapter) {
        this.gson = gson;
        this.adapter = adapter;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {
        try {
            String originalBody = value.string();
            // 解密
            String body = EncryptUtils.decryptParams(originalBody);
            // 獲取json中的code,對json進行預處理
            JSONObject json = new JSONObject(body);
            int code = json.optInt("code");
            // 當code不為0時,設置data為{},這樣轉化就不會出錯了
            if (code != 0) {
                json.put("data", new JSONObject());
                body = json.toString();
            }

            return adapter.fromJson(body);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        } finally {
            value.close();
        }
    }

這里也貼一下原版的GsonRequestBodyConverter

class GsonRequestBodyConverter<T> implements Converter<T, RequestBody> {
  private static final MediaType MEDIA_TYPE = MediaType.parse("application/json; charset=UTF-8");
  private static final Charset UTF_8 = Charset.forName("UTF-8");

  private final Gson gson;
  private final TypeAdapter<T> adapter;

  GsonRequestBodyConverter(Gson gson, TypeAdapter<T> adapter) {
    this.gson = gson;
    this.adapter = adapter;
  }

  @Override public RequestBody convert(T value) throws IOException {
    Buffer buffer = new Buffer();
    Writer writer = new OutputStreamWriter(buffer.outputStream(), UTF_8);
    JsonWriter jsonWriter = gson.newJsonWriter(writer);
    adapter.write(jsonWriter, value);
    jsonWriter.close();
    return RequestBody.create(MEDIA_TYPE, buffer.readByteString());
  }
}

這樣build.gradle中就可以刪掉引入的GsonConverterFactory

整合使用

使用方式如下

Retrofit retrofit = new Retrofit.Builder()
                .client(getOkHttpClient())
                .addConverterFactory(CustomGsonConverterFactory.create())
                .baseUrl(BASE_URL)
                .build();

其中,okhttpClient方法:

@NonNull
private OkHttpClient getOkHttpClient() {
    OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder();
    okHttpClientBuilder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
            .writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
            .readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
            .addInterceptor(new RequestHeaderInterceptor())
            .addInterceptor(new RequestEncryptInterceptor())
            .addInterceptor(new GzipRequsetInterceptor());
    return okHttpClientBuilder.build();
}

就醬

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。