2015-02-24 16 views
35

Tôi đang sử dụng một máy đánh chặn, và tôi muốn đăng nhập cơ thể của một yêu cầu tôi đang làm nhưng tôi không thể nhìn thấy bất kỳ cách nào để làm điều này.OkHttp làm thế nào để đăng nhập yêu cầu cơ thể

Có thể không?

public class LoggingInterceptor implements Interceptor { 
    @Override 
    public Response intercept(Chain chain) throws IOException { 
     Request request = chain.request(); 

     long t1 = System.nanoTime(); 
     Response response = chain.proceed(request); 
     long t2 = System.nanoTime(); 

     double time = (t2 - t1)/1e6d; 

     if (request.method().equals("GET")) { 
      Logs.info(String.format("GET " + F_REQUEST_WITHOUT_BODY + F_RESPONSE_WITH_BODY, request.url(), time, request.headers(), response.code(), response.headers(), response.body().charStream())); 
     } else if (request.method().equals("POST")) { 
      Logs.info(String.format("POST " + F_REQUEST_WITH_BODY + F_RESPONSE_WITH_BODY, request.url(), time, request.headers(), request.body(), response.code(), response.headers(), response.body().charStream())); 
     } else if (request.method().equals("PUT")) { 
      Logs.info(String.format("PUT " + F_REQUEST_WITH_BODY + F_RESPONSE_WITH_BODY, request.url(), time, request.headers(), request.body().toString(), response.code(), response.headers(), response.body().charStream())); 
     } else if (request.method().equals("DELETE")) { 
      Logs.info(String.format("DELETE " + F_REQUEST_WITHOUT_BODY + F_RESPONSE_WITHOUT_BODY, request.url(), time, request.headers(), response.code(), response.headers())); 
     } 

     return response; 
    } 
} 

và kết quả:

POST [some url] in 88,7ms 
    ZoneName: touraine 
    Source: Android 
    body: [email protected] <-request.body().toString() gives me this, but I would like the content string 
    Response: 500 
    Date: Tue, 24 Feb 2015 10:14:22 GMT 
    body: [some content] 

Trả lời

77

câu trả lời Nikola đã không làm việc cho tôi. Tôi đoán là việc thực hiện ByteString#toString() đã thay đổi. Giải pháp này làm việc cho tôi:

private static String bodyToString(final Request request){ 

    try { 
     final Request copy = request.newBuilder().build(); 
     final Buffer buffer = new Buffer(); 
     copy.body().writeTo(buffer); 
     return buffer.readUtf8(); 
    } catch (final IOException e) { 
     return "did not work"; 
    } 
} 

Từ các tài liệu của readUtf8():

Loại bỏ tất cả các byte từ này, giải mã chúng như UTF-8, và trả về chuỗi.

nên là thứ bạn muốn.

+0

Cảm ơn bạn rất nhiều, nó hoạt động như một nét duyên dáng:) –

+0

Chỉ trong trường hợp, bạn cũng biết cách làm điều này bằng cách sử dụng một đối tượng Response? (sao chép nội dung phản hồi) –

+1

@MathieudeBrito thử 'response.body(). string()'. – aga

8

Tôi đã cố gắng nhận xét về câu trả lời đúng từ @msung, nhưng danh tiếng của tôi không đủ cao.

Đây là sửa đổi tôi đã thực hiện để in RequestBody trước khi đưa ra yêu cầu đầy đủ. Nó hoạt động như một say mê. Cảm ơn

private static String bodyToString(final RequestBody request){ 
     try { 
      final RequestBody copy = request; 
      final Buffer buffer = new Buffer(); 
      copy.writeTo(buffer); 
      return buffer.readUtf8(); 
     } 
     catch (final IOException e) { 
      return "did not work"; 
     } 
} 
+0

nó chỉ trả lại một tập hợp các chuỗi ngẫu nhiên. không hoạt động – pks

+0

Bạn đã đăng chuỗi nó theo bất kỳ cách nào? – bold

+0

không, tôi chưa đăng ký nó ...bạn có thể vui lòng chỉnh sửa câu trả lời của bạn để làm tất cả các công cụ theo cách chính xác để in nội dung yêu cầu – pks

8

EDIT

Bởi vì tôi thấy vẫn còn một số người quan tâm qua đường bưu điện này, đây là phiên bản cuối cùng (cho đến khi cải thiện tiếp theo) của đánh chặn đăng nhập của tôi. Tôi hy vọng nó sẽ tiết kiệm thời gian của các bạn.

Xin lưu ý rằng mã này được sử dụng OkHttp 2.2.0 (và Retrofit 1.9.0)

import com.squareup.okhttp.*; 
import okio.Buffer; 
import java.io.IOException; 

public class LoggingInterceptor implements Interceptor { 

private static final String F_BREAK = " %n"; 
private static final String F_URL = " %s"; 
private static final String F_TIME = " in %.1fms"; 
private static final String F_HEADERS = "%s"; 
private static final String F_RESPONSE = F_BREAK + "Response: %d"; 
private static final String F_BODY = "body: %s"; 

private static final String F_BREAKER = F_BREAK + "-------------------------------------------" + F_BREAK; 
private static final String F_REQUEST_WITHOUT_BODY = F_URL + F_TIME + F_BREAK + F_HEADERS; 
private static final String F_RESPONSE_WITHOUT_BODY = F_RESPONSE + F_BREAK + F_HEADERS + F_BREAKER; 
private static final String F_REQUEST_WITH_BODY = F_URL + F_TIME + F_BREAK + F_HEADERS + F_BODY + F_BREAK; 
private static final String F_RESPONSE_WITH_BODY = F_RESPONSE + F_BREAK + F_HEADERS + F_BODY + F_BREAK + F_BREAKER; 

@Override 
public Response intercept(Chain chain) throws IOException { 
    Request request = chain.request(); 

    long t1 = System.nanoTime(); 
    Response response = chain.proceed(request); 
    long t2 = System.nanoTime(); 

    MediaType contentType = null; 
    String bodyString = null; 
    if (response.body() != null) { 
     contentType = response.body().contentType(); 
     bodyString = response.body().string(); 
    } 

    double time = (t2 - t1)/1e6d; 

    if (request.method().equals("GET")) { 
     System.out.println(String.format("GET " + F_REQUEST_WITHOUT_BODY + F_RESPONSE_WITH_BODY, request.url(), time, request.headers(), response.code(), response.headers(), stringifyResponseBody(bodyString))); 
    } else if (request.method().equals("POST")) { 
     System.out.println(String.format("POST " + F_REQUEST_WITH_BODY + F_RESPONSE_WITH_BODY, request.url(), time, request.headers(), stringifyRequestBody(request), response.code(), response.headers(), stringifyResponseBody(bodyString))); 
    } else if (request.method().equals("PUT")) { 
     System.out.println(String.format("PUT " + F_REQUEST_WITH_BODY + F_RESPONSE_WITH_BODY, request.url(), time, request.headers(), request.body().toString(), response.code(), response.headers(), stringifyResponseBody(bodyString))); 
    } else if (request.method().equals("DELETE")) { 
     System.out.println(String.format("DELETE " + F_REQUEST_WITHOUT_BODY + F_RESPONSE_WITHOUT_BODY, request.url(), time, request.headers(), response.code(), response.headers())); 
    } 

    if (response.body() != null) { 
     ResponseBody body = ResponseBody.create(contentType, bodyString); 
     return response.newBuilder().body(body).build(); 
    } else { 
     return response; 
    } 
} 


private static String stringifyRequestBody(Request request) { 
    try { 
     final Request copy = request.newBuilder().build(); 
     final Buffer buffer = new Buffer(); 
     copy.body().writeTo(buffer); 
     return buffer.readUtf8(); 
    } catch (final IOException e) { 
     return "did not work"; 
    } 
} 

public String stringifyResponseBody(String responseBody) { 
    return responseBody; 
} 
} 
+1

Nếu bạn có thể đăng tải lên hàng đầu, nó sẽ rất hữu ích vì có nhiều phiên bản của OKHttp và tôi đang chơi đoán và kiểm tra để tìm ra những cái bạn có ở đây. Cảm ơn bạn – Silmarilos

+0

Thực hiện, hy vọng nó sẽ giúp;) –

+0

Nó, cảm ơn bạn rất nhiều cho Mathieu làm rõ. – Silmarilos

1

Version để xử lý yêu cầu có hoặc không có một cơ thể:

private String stringifyRequestBody(Request request) { 
    if (request.body() != null) { 
     try { 
      final Request copy = request.newBuilder().build(); 
      final Buffer buffer = new Buffer(); 
      copy.body().writeTo(buffer); 
      return buffer.readUtf8(); 
     } catch (final IOException e) { 
      Log.w(TAG, "Failed to stringify request body: " + e.getMessage()); 
     } 
    } 
    return ""; 
} 
Các vấn đề liên quan