根据请求进行改造设置标记,并返回响应

时间:2015-04-10 19:46:14

标签: android retrofit

基本上,我的问题很简单。我正在使用改造作为与我无法控制的服务器进行通信的框架。我想在我的请求上设置某种标记,它会自动在响应中返回。关于如何实现这一点的任何想法?

1 个答案:

答案 0 :(得分:0)

我发现了一种复杂且不太酷的方法。

<强> 0。在请求和响应类型中添加标记字段

<强> 1。自定义 <receiver android:name=".utils.DelayedStartServiceBroadcastReceiver" android:enabled="true" android:exported="true" > </receiver> 添加标记字段:

<强> 2。自定义okhttp3.RequestBody添加标记字段:

第3。自定义okhttp3.ResponseBody设置并获取代码:
例如,我对Converter.FactoryGsonResponseBodyConverter进行了一些更改:

TagGsonRequestBodyConverter.java:

GsonRequestBodyConverter

TagGsonResponseBodyConverter.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;
  }

}

<强> 4。在创建改造的okhttpClient时添加拦截器,将标记从TagRequestBody传递到TagResponseBody:

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

因此标签被保持:
RequestDataWithTag - CustGsonRequestBodyConverter - &gt; RequestBodyWithTag - 拦截器 - &gt; ResponseBodyWithTag - CustGsonResponseBodyConverter - &gt; ResponseDataWithTag