Java 如何更改OkHttp响应中的正文?

Java 如何更改OkHttp响应中的正文?,java,android,retrofit,interceptor,okhttp,Java,Android,Retrofit,Interceptor,Okhttp,我正在使用改装。要捕获响应,我正在使用拦截器: OkHttpClient okHttpClient = new OkHttpClient(); okHttpClient.interceptors().add(myinterceptor); new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request request = chain

我正在使用改装。要捕获响应,我正在使用拦截器:

OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.interceptors().add(myinterceptor);
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
以下是拦截器的代码:

OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.interceptors().add(myinterceptor);
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
如何在OkHttp响应中更改正文?

添加此选项

MediaType contentType = response.body().contentType();
ResponseBody body = ResponseBody.create(contentType, jsonObject);
return response.newBuilder().body(body).build();

在您的回复修改后
jsonObject
是要返回的修改后的JSON。

下面是响应拦截器类,您可以在其中截获OKHTTP响应并添加自己的响应。然后把它送去改装

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;
    }
}
Yow将在您的改装回调中获得您修改的响应

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) {

            }
        });
call.enqueue(新回调(){
@凌驾
公共void onResponse(调用、响应){
//您将在此处获得自己的修改响应
}
@凌驾
失败时公共无效(调用调用,可丢弃的t){
}
});

作为一个小改动,我不会使用
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"));

下面是一个添加拦截器的完整示例,该拦截器将JSON修改为。它用于管理JSON

        client.addInterceptor(chain -> {
            final Request request = chain.request();
            final String path = request.url().uri().getPath();
            final Response response = chain.proceed(request);

            String body = response.body().string();
            final JsonElement element = new JsonParser().parse(body);
            if ("/the/endpoint/you/want/to/modify".equals(path)){
                final JsonObject object = element.getAsJsonObject();
                // v v v v v v All this for these lines v v v v v v v
                object.addProperty("some_json_name","some_json_value");
                object.addProperty("existing_property","updated_value");
                object.addProperty("numbers_work_too",1.2);
                // ^ ^ ^ ^ ^ ^ All this for these lines ^ ^ ^ ^ ^ ^ ^
                body = object.toString();
            }
            return response.newBuilder().body(ResponseBody.create(response.body().contentType(), body)).build();
        });

您面临的问题是什么?我需要将这个新的json设置为response,然后返回这个响应,怎么做?