安卓okhttp 打印请求数据
时间: 2023-07-25 15:25:38 浏览: 112
Android-基于RxJava封装的OkHttp网络请求库
在 OkHttp 中,可以通过拦截器来打印请求和响应数据。以下是一个简单的拦截器示例,可以用于打印请求数据:
```java
public class LoggingInterceptor implements Interceptor {
@Override public Response intercept(Interceptor.Chain chain) throws IOException {
Request request = chain.request();
long t1 = System.nanoTime();
Log.d("OkHttp", String.format("Sending request %s on %s%n%s",
request.url(), chain.connection(), request.headers()));
Response response = chain.proceed(request);
long t2 = System.nanoTime();
Log.d("OkHttp", String.format("Received response for %s in %.1fms%n%s",
response.request().url(), (t2 - t1) / 1e6d, response.headers()));
MediaType contentType = response.body().contentType();
String bodyString = response.body().string();
Log.d("OkHttp", "response body:" + bodyString);
Response newResponse = response.newBuilder()
.body(ResponseBody.create(contentType, bodyString))
.build();
return newResponse;
}
}
```
在使用 OkHttp 发送请求时,只需将上面的拦截器添加到 OkHttpClient 中即可:
```java
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new LoggingInterceptor())
.build();
```
添加后,每次发送请求时,都会在 Logcat 中打印请求和响应数据。
阅读全文