okhttp3怎么添加请求头
时间: 2024-06-15 15:02:47 浏览: 98
在OkHttp3中,可以通过拦截器Interceptor来添加请求头。以下是两种添加请求头的方法:
1. 使用Interceptor添加请求头[^1]:
```java
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request originalRequest = chain.request();
Request.Builder requestBuilder = originalRequest.newBuilder()
.header("HeaderName", "HeaderValue")
.header("AnotherHeaderName", "AnotherHeaderValue");
Request newRequest = requestBuilder.build();
return chain.proceed(newRequest);
}
})
.build();
```
2. 使用Interceptor和Headers.Builder添加请求头:
```java
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request originalRequest = chain.request();
Headers.Builder headersBuilder = originalRequest.headers().newBuilder()
.add("HeaderName", "HeaderValue")
.add("AnotherHeaderName", "AnotherHeaderValue");
Request newRequest = originalRequest.newBuilder()
.headers(headersBuilder.build())
.build();
return chain.proceed(newRequest);
}
})
.build();
```
阅读全文