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

问题描述 投票:0回答:6

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

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 中的正文?

java android retrofit interceptor okhttp
6个回答
39
投票

添加这个

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

您的回复修改后。

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


18
投票

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

您将在改造回调中获得修改后的响应

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

            }
        });

10
投票

作为一个小改动,我不会使用

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"));

3
投票

这是一个紧凑、完整的示例,添加了一个将 JSON 修改为

OkHttpClient
的拦截器。它使用 GSON 来管理 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();
        });

0
投票
   JSONObject postdata = new JSONObject();
            try {

                postdata.put("citizenId", "2222222222222");
                postdata.put("accuracy", 3043.323);
                postdata.put("provider", "wifi");
                postdata.put("gpsTime", 1111111111111L);
                postdata.put("lat", 23434.564);
                postdata.put("lng", 34343.5445);
                postdata.put("appId", "201");

            } catch(JSONException e){
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            RequestBody body = RequestBody.create(MEDIA_TYPE,postdata.toString());

            HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
            interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            final OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();

        //    final OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();


            final Request request = new Request.Builder()
                    .url(base_url)
                    .post(body)
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Authorization", "JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJvd25lcklkIjoyLCJvd25lclR5cGUiOiJMRUFERVIiLCJpYXQiOjE1MDE4Mjc4MDMsImV4cCI6MzMwMzc4Mjc4MDMsImF1ZCI6InNlbmRpdC5hc2lhIiwiaXNzIjoic2VsZiJ9.3Gpn3beZfdYsMOLTjksLwmxyfbrfqiojdm1n-gh6CXY")
                    .addHeader("cache-control", "no-cache")
                    .build();


            client.newCall(request).enqueue(new Callback() {

                @SuppressLint("LongLogTag")
                @Override
                public void onResponse(Call call, Response response) throws IOException {

                    try {
    //                    response = client.newCall(request).execute();
    //                    Protocol protocol = response.protocol();
    //                    assertEquals(Protocol.HTTP_1_1, protocol);

    //                    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"));

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

                        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"));

                                Log.e("response body responseBodyString ", body.string());
                                Log.e("response body responseBodyString  ", responseBodyString);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }


                        Log.e("response", String.valueOf(response));
                        Log.e("response body", String.valueOf(response.body()));

                    } }catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(Call call, IOException e) {
                    Log.e("response  onFailure ", String.valueOf(e));
                }

            });

0
投票

create()
函数已被弃用,并替换为
.toResponseBody()
.asResponseBody()
扩展。

OkHttpClient.Builder().apply {
    addInterceptor { chain ->
        // modifiedBodyString is created here ...

        val contentType = response.body().contentType();

        // Old approach (Deprecated):
        val responseBody = ResponseBody.create(contentType, modifiedBodyString);

        // New approach:
        val responseBody = modifiedBodyString.toResponseBody(contentType)

        response.newBuilder().body(responseBody).build(); 
    }
}.build()

我使用的是OkHttp版本4.10.0。

© www.soinside.com 2019 - 2024. All rights reserved.