2016-03-03 15 views
10

Tôi đang sử dụng trang bị thêm. Để bắt phản ứng Tôi đang sử dụng Interceptor:Làm thế nào để thay đổi nội dung trong OkHttp Response?

OkHttpClient okHttpClient = new OkHttpClient(); 
okHttpClient.interceptors().add(myinterceptor); 

đây là mã của đánh chặn:

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 

Làm thế nào để thay đổi cơ thể trong OkHttp đáp ứng?

+0

vấn đề bạn đang gặp phải là gì? – Rohit5k2

+0

Tôi cần thiết lập json mới này để phản hồi và sau đó trả lại phản hồi này, cách thực hiện điều đó? – NickUnuchek

Trả lời

17

Thêm này

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

sau khi chỉnh sửa câu trả lời của bạn. jsonObject là JSON đã sửa đổi bạn muốn trả lại.

3

Dưới đây là lớp Intercepter Response, nơi bạn có thể chặn phản hồi okkhttp và thêm phản hồi của riêng bạn. và gửi nó để trang bị thêm.

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 sẽ nhận được phản ứng biến đổi của bạn ở đây trong trang bị thêm bạn gọi lại

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

      } 
     }); 
0

Là một thay đổi nhỏ tôi sẽ không sử dụng phương pháp string() nguyên nhân nó có thể được gọi là một lần duy nhất theo yêu cầu này. Bạn sử dụng response.newBuilder() để những kẻ đánh chặn khác trong chuỗi sẽ có thể gọi string() trên cái mới của bạn nhưng tôi thấy mình lãng phí một vài giờ vì tôi đã thực sự gọi nó hai lần: P.

Vì vậy, tôi đề nghị một cái gì đó như sau

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

      }); 
Các vấn đề liên quan