Retrofit2中拦截器中的chain.request()返回null

时间:2016-11-08 20:29:02

标签: android retrofit2

我正在尝试将HMAC添加到标头中。它工作正常。但是在某些设备上随机抛出NPE。以下是完整的代码。

使用okhttp v3.4.1,okio v1.9.0&改造v2.1.0

OkHttpClient.Builder okHttp = new OkHttpClient().newBuilder();
okHttp.connectTimeout(Constants.CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS);
okHttp.readTimeout(Constants.CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS);
okHttp.writeTimeout(Constants.CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS);
okHttp.retryOnConnectionFailure(false); 
okHttp.addInterceptor(new Interceptor() {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request.Builder requestBuilder;
        Request request = null;

        try {
            String requestUrl = chain.request().url().toString();       //NPE issue : Attempt to invoke virtual method 'okhttp3.HttpUrl okhttp3.Request.url()' on a null object reference

            requestBuilder = chain.request().newBuilder()
                    .addHeader("hmac", generateHmac(requestUrl))
                    .addHeader("somemoreHeaders", "values");

            if(additionalHeaders != null && !additionalHeaders.isEmpty()) {
                Set<Map.Entry<String, String>> entries = additionalHeaders.entrySet();

                for (Map.Entry<String, String> header : entries) {
                    requestBuilder.addHeader(header.getKey(), URLEncoder.encode((auth.getEncodedData(header.getValue())), context.getString(R.string.charSet)));
                }
            }

            request = requestBuilder.build();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return chain.proceed(request);
    }
});

okHttp.build();

这是我的例外:

Fatal Exception: java.lang.NullPointerException: Attempt to invoke virtual method 'okhttp3.HttpUrl okhttp3.Request.url()' on a null object reference
    at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(SourceFile:111)
    at okhttp3.internal.http.RealInterceptorChain.proceed(SourceFile:92)
    at okhttp3.internal.http.RealInterceptorChain.proceed(SourceFile:67)
    at mypackage.client.RetrofitClient$2.intercept(SourceFile:112)
    at okhttp3.internal.http.RealInterceptorChain.proceed(SourceFile:92)
    at okhttp3.internal.http.RealInterceptorChain.proceed(SourceFile:67)
    at okhttp3.RealCall.getResponseWithInterceptorChain(SourceFile:170)
    at okhttp3.RealCall.access$100(SourceFile:33)
    at okhttp3.RealCall$AsyncCall.execute(SourceFile:120)
    at okhttp3.internal.NamedRunnable.run(SourceFile:32)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
    at java.lang.Thread.run(Thread.java:818)

0 个答案:

没有答案