如何在OkHttp Response中更改正文?

2022-09-01 19:53:01

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

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 Response中更改正文?


答案 1

添加此

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

在响应修改后。 是要返回的已修改 JSON。jsonObject


答案 2

下面是响应拦截器类,您可以在其中拦截 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;
    }
}

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

            }
        });

推荐