基本上,我的问题很简单。我使用改造作为与我无法控制的服务器进行通信的框架。我想在我的请求上设置某种标记,该标记会自动在响应中返回。关于如何实现这一点有什么想法吗?
我找到了一种复杂且不太酷的方法来做到这一点。
0. 在请求和响应类型中添加标签字段
1.自定义okhttp3.RequestBody添加标签字段:
2.自定义okhttp3.ResponseBody添加标签字段:
3.自定义Converter.Factory设置和获取标签:
例如我对GsonResponseBodyConverterand做了一些更改GsonRequestBodyConverter:
TagGsonRequestBodyConverter.java:
@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();
TagRequestBody requestBody = TagRequestBody.create(MEDIA_TYPE, buffer.readByteString());
requestBody = value.tag;//just for example ,you will need to check type here
return requestBody;
}
Run Code Online (Sandbox Code Playgroud)
TagGsonResponseBodyConverter.java:
@Override public T convert(ResponseBody source) throws IOException {
try {
//the ugly part,for that retrofit will wrap the responseBody with ExceptionCatchingRequestBody.(ExceptionCatchingRequestBody extends ResponseBody)
ResponseBody value = source;
if (value.getClass().getSimpleName().equals("ExceptionCatchingRequestBody")){
ResponseBody temp = null;
try {
Field f = source.getClass().getDeclaredField("delegate");
f.setAccessible(true);
temp = (T) f.get(value);
} catch (Exception e) {
e.printStackTrace();
}
value = temp != null?temp:value;
}
T t = adapter.fromJson(source.charStream());
if (value instanceof TagResponseBody) {
t.tag = ((TagResponseBody)value).tag;
}
return t;
} finally {
value.close();
}
Run Code Online (Sandbox Code Playgroud)
}
4.创建retrofit的okhttpClient时添加Interceptor,将标签从TagRequestBody传递到TagResponseBody:
.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Response response = chain.proceed(chain.request());
if (request.body() instanceof TagRequestBody) {
TagResponseBody responseBody = new TagResponseBody(response.body());
responseBody.arg = ((TagRequestBody) request.body()).arg;
response = response.newBuilder()
.body(responseBody)
.build();
}
return response;
}
})
Run Code Online (Sandbox Code Playgroud)
因此,标签由以下内容持有:
RequestDataWithTag -- CustGsonRequestBodyConverter --> RequestBodyWithTag -- Interceptor --> ResponseBodyWithTag -- CustGsonResponseBodyConverter --> ResponseDataWithTag
| 归档时间: |
|
| 查看次数: |
2698 次 |
| 最近记录: |