Nic*_*hek 18 java android interceptor retrofit okhttp
我正在使用改造.要捕获响应,我正在使用Interceptor:
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.interceptors().add(myinterceptor);
Run Code Online (Sandbox Code Playgroud)
这是拦截器的代码:
new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Response response = chain.proceed(request);
if (path.equals("/user")){
String stringJson = response.body().string();
JSONObject jsonObject = new JSONObject(stringJson);
jsonObject.put("key",1);
//here I need to set this new json to response and then return this response
Run Code Online (Sandbox Code Playgroud)
如何在OkHttp响应中更改正文?
Roh*_*5k2 33
加上这个
MediaType contentType = response.body().contentType();
ResponseBody body = ResponseBody.create(contentType, jsonObject);
return response.newBuilder().body(body).build();
Run Code Online (Sandbox Code Playgroud)
在您的回复修改后.jsonObject
是您要返回的已修改JSON.
小智 8
下面是Response Intercepter类,您可以在其中拦截okkhttp响应并添加您自己的响应.并将其发送给改造.
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.ResponseBody;
import retrofit2.Response;
public class ApiResponseInterceptor implements Interceptor {
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request request = chain.request();
okhttp3.Response response = chain.proceed(request);
if(response.code() == 200) {
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("code",200);
jsonObject.put("status","OK");
jsonObject.put("message","Successful");
MediaType contentType = response.body().contentType();
ResponseBody body = ResponseBody.create(contentType, jsonObject.toString());
return response.newBuilder().body(body).build();
} catch (JSONException e) {
e.printStackTrace();
}
} else if(response.code() == 403) {
}
return response;
}
}
Run Code Online (Sandbox Code Playgroud)
您将在改装回调中获得修改后的响应
call.enqueue(new Callback<EventResponce>() {
@Override
public void onResponse(Call<EventResponce> call, Response<EventResponce> response) {
// you will get your own modified responce here
}
@Override
public void onFailure(Call<EventResponce> call, Throwable t) {
}
});
Run Code Online (Sandbox Code Playgroud)
作为一个较小的更改,我不会使用该string()
方法,因为在此请求上只能调用一次。您确实使用了response.newBuilder()
其他拦截器,因此可以调用string()
您的新拦截器,但是我发现自己浪费了几个小时,因为我实际上两次调用了:P。
所以我建议如下
BufferedSource source = response.body().source();
source.request(Long.MAX_VALUE); // Buffer the entire body.
Buffer buffer = source.buffer();
String responseBodyString = buffer.clone().readString(Charset.forName("UTF-8"));
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
16521 次 |
最近记录: |