如何将标头添加到 OkHttp 请求拦截器?

2022-08-31 09:12:51

我有这个拦截器,我添加到我的OkHttp客户端:

public class RequestTokenInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
  Request request = chain.request();
  // Here where we'll try to refresh token.
  // with an retrofit call
  // After we succeed we'll proceed our request
  Response response = chain.proceed(request);
  return response;
}
}

如何在我的拦截器中添加要请求的标头?

我试过这个,但我犯了错误,我在创建新请求时丢失了我的请求:

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

        try {
            Log.d("addHeader", "Before");
            String token = TokenProvider.getInstance(mContext).getToken();
            newRequest = request.newBuilder()
                    .addHeader(HeadersContract.HEADER_AUTHONRIZATION, O_AUTH_AUTHENTICATION + token)
                    .addHeader(HeadersContract.HEADER_CLIENT_ID, CLIENT_ID)
                    .build();
        } catch (Exception e) {
            Log.d("addHeader", "Error");
            e.printStackTrace();
            return chain.proceed(request);
        }

        Log.d("addHeader", "after");
        return chain.proceed(newRequest);
    }
}

请注意,我知道我可以在创建这样的请求时添加标头:

Request request = new Request.Builder()
    .url("https://api.github.com/repos/square/okhttp/issues")
    .header("User-Agent", "OkHttp Headers.java")
    .addHeader("Accept", "application/json; q=0.5")
    .addHeader("Accept", "application/vnd.github.v3+json")
    .build();

但它不符合我的需求。我在拦截器中需要它。


答案 1

最后,我以这种方式添加了标头:

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

        newRequest = request.newBuilder()
                .addHeader(HeadersContract.HEADER_AUTHONRIZATION, O_AUTH_AUTHENTICATION)
                .addHeader(HeadersContract.HEADER_X_CLIENT_ID, CLIENT_ID)
                .build();
        return chain.proceed(newRequest);
    }

答案 2

你可以这样做

private String GET(String url, Map<String, String> header) throws IOException {
        Headers headerbuild = Headers.of(header);
        Request request = new Request.Builder().url(url).headers(headerbuild).
                        build();

        Response response = client.newCall(request).execute();
        return response.body().string();
    }

推荐