android Retrofit2 返回json客户端与服务端加

2020-10-05  本文已影响0人  张漂亮1号

对response进行解密,retrofit设置自定义的ConverterFactory,因客户端与服务端使用json通信,因此我们参考官方提供GsonConverterFactory编写

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

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();
        }
    }

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());
  }
}

image
借鉴原文https://blog.csdn.net/weixin_43901866/article/details/86578148
上一篇 下一篇

猜你喜欢

热点阅读