对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);
JSONObject json = new JSONObject(body);
int code = json.optInt("code");
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())
}
}
借鉴原文blog.csdn.net/weixin_4390…