2016-01-14 16 views
15

Tôi đang sử dụng Retrofit 2 (2.0.0-beta3) với ứng dụng OkHttp trong ứng dụng Android và cho đến nay mọi thứ trở nên tuyệt vời. Nhưng hiện tại tôi đang gặp vấn đề với OkHttp Interceptor. Máy chủ tôi đang giao tiếp đang lấy mã thông báo truy cập trong phần thân yêu cầu, vì vậy khi tôi chặn yêu cầu thêm mã thông báo xác thực hoặc trong phương thức xác thực Authenticator khi tôi cần thêm mã thông báo cập nhật, tôi cần sửa đổi yêu cầu cho mục đích này . Nhưng có vẻ như tôi chỉ có thể thêm dữ liệu vào tiêu đề chứ không phải trong nội dung yêu cầu đang diễn ra. Mã tôi đã viết cho đến nay như sau:Retrofit2: Sửa đổi thân yêu cầu trong Thiết bị chặn OkHttp

client.interceptors().add(new Interceptor() { 
      @Override 
      public Response intercept(Chain chain) throws IOException { 
       Request request = chain.request(); 
       if (UserPreferences.ACCESS_TOKEN != null) { 
        // need to add this access token in request body as encoded form field instead of header 
        request = request.newBuilder() 
          .header("access_token", UserPreferences.ACCESS_TOKEN)) 
          .method(request.method(), request.body()) 
          .build(); 
       } 
       Response response = chain.proceed(request); 
       return response; 
      } 
     }); 

bất cứ ai có thể chỉ cho tôi đi đúng hướng như thế nào để sửa đổi theo yêu cầu cơ thể để thêm thẻ truy cập của tôi (lần đầu tiên hoặc cập nhật sau khi refresh token)? Bất kỳ con trỏ nào đến đúng hướng sẽ được đánh giá cao.

Trả lời

16

Tôi sử dụng tính năng này để thêm thông số bài đăng vào các thông số hiện có.

OkHttpClient client = new OkHttpClient.Builder() 
        .protocols(protocols) 
        .addInterceptor(new Interceptor() { 
         @Override 
         public Response intercept(Chain chain) throws IOException { 
          Request request = chain.request(); 
          Request.Builder requestBuilder = request.newBuilder(); 
RequestBody formBody = new FormEncodingBuilder() 
      .add("email", "[email protected]") 
      .add("tel", "90301171XX") 
      .build(); 
          String postBodyString = Utils.bodyToString(request.body()); 
          postBodyString += ((postBodyString.length() > 0) ? "&" : "") + Utils.bodyToString(formBody); 
          request = requestBuilder 
            .post(RequestBody.create(MediaType.parse("application/x-www-form-urlencoded;charset=UTF-8"), postBodyString)) 
            .build(); 
          return chain.proceed(request); 
         } 
        }) 
        .build(); 

public static String bodyToString(final RequestBody request){ 
     try { 
      final RequestBody copy = request; 
      final Buffer buffer = new Buffer(); 
      if(copy != null) 
       copy.writeTo(buffer); 
      else 
       return ""; 
      return buffer.readUtf8(); 
     } 
     catch (final IOException e) { 
      return "did not work"; 
     } 
    } 

OkHttp3:

RequestBody formBody = new FormBody.Builder() 
       .add("email", "[email protected]") 
       .add("tel", "90301171XX") 
       .build(); 
+0

nó sẽ là một ý tưởng tốt để đóng bộ đệm trong 'bodyToString()' trước khi trở –

+0

@ 3k thats không cần thiết, Buffer doesnt phân bổ bất cứ điều gì có thể được đóng bên trong constructor. https://github.com/square/okio/blob/master/okio/src/main/java/okio/Buffer.java#L59 – Fabian

1

Vì đây không thể được viết trong các ý kiến ​​của các câu trả lời trước bởi @Fabian, tôi gửi bài này là câu trả lời riêng biệt. Câu trả lời này đề cập đến cả "ứng dụng/json" cũng như dữ liệu biểu mẫu.

import android.content.Context; 

import org.json.JSONException; 
import org.json.JSONObject; 

import java.io.IOException; 

import okhttp3.FormBody; 
import okhttp3.Interceptor; 
import okhttp3.MediaType; 
import okhttp3.Request; 
import okhttp3.RequestBody; 
import okhttp3.Response; 
import okio.Buffer; 

/** 
* Created by debanjan on 16/4/17. 
*/ 

public class TokenInterceptor implements Interceptor { 
    private Context context; //This is here because I needed it for some other cause 

    //private static final String TOKEN_IDENTIFIER = "token_id"; 
    public TokenInterceptor(Context context) { 
     this.context = context; 
    } 

    @Override 
    public Response intercept(Chain chain) throws IOException { 
     Request request = chain.request(); 
     RequestBody requestBody = request.body(); 
     String token = "toku";//whatever or however you get it. 
     String subtype = requestBody.contentType().subtype(); 
     if(subtype.contains("json")){ 
      requestBody = processApplicationJsonRequestBody(requestBody, token); 
     } 
     else if(subtype.contains("form")){ 
      requestBody = processFormDataRequestBody(requestBody, token); 
     } 
     if(requestBody != null) { 
      Request.Builder requestBuilder = request.newBuilder(); 
      request = requestBuilder 
        .post(requestBody) 
        .build(); 
     } 

     return chain.proceed(request); 
    } 
    private String bodyToString(final RequestBody request){ 
     try { 
      final RequestBody copy = request; 
      final Buffer buffer = new Buffer(); 
      if(copy != null) 
       copy.writeTo(buffer); 
      else 
       return ""; 
      return buffer.readUtf8(); 
     } 
     catch (final IOException e) { 
      return "did not work"; 
     } 
    } 
    private RequestBody processApplicationJsonRequestBody(RequestBody requestBody,String token){ 
     String customReq = bodyToString(requestBody); 
     try { 
      JSONObject obj = new JSONObject(customReq); 
      obj.put("token", token); 
      return RequestBody.create(requestBody.contentType(), obj.toString()); 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 
     return null; 
    } 
    private RequestBody processFormDataRequestBody(RequestBody requestBody, String token){ 
     RequestBody formBody = new FormBody.Builder() 
       .add("token", token) 
       .build(); 
     String postBodyString = bodyToString(requestBody); 
     postBodyString += ((postBodyString.length() > 0) ? "&" : "") + bodyToString(formBody); 
     return RequestBody.create(requestBody.contentType(), postBodyString); 
    } 

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