Okhttp 拦截器问题

huangapple go评论80阅读模式
英文:

Okhttp Interceptor issue

问题

我正在尝试为一个简单的okhttpGet请求添加一个头部如何正确添加HttpHeader我可以进行调试以确保我的头部实际上被发送到服务器吗

Request request = new Request.Builder()
        .url("URL")
        .build();

OkHttpClient okHttpClient = new OkHttpClient.Builder()
        .addInterceptor(new Interceptor() {
            @Override
            public okhttp3.Response intercept(Chain chain) throws IOException {
                Request originalRequest = chain.request();
                Request newRequest = originalRequest.newBuilder()
                        .addHeader("Header", "123")
                        .build();
                return chain.proceed(newRequest);
            }
        })
        .build();

okHttpClient.newCall(request).enqueue(new Callback() {
    @Override
    public void onFailure(Call call, IOException e) {
    }
});

我已经寻找了基本的简单示例,但它们都是关于Retrofit、GSON、接口或者是使用Kotlin的。我需要在代码中理解这部分内容。

英文:

I'm trying to add a header to a simple okhttp (Get) request. How do I add the HttpHeader properly? Can I debug to ensure that my Header is actually sent to the server?

        Request request = new Request.Builder()
                .url("URL")
                .build();

        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(new Interceptor() {
                    @Override
                    public okhttp3.Response intercept(Chain chain) throws IOException {
                        Request originalRequest = chain.request();
                        Request newRequest = originalRequest.newBuilder()
                                .addHeader("Header", "123")
                                .build();
                        return chain.proceed(newRequest);
                    }
                })
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
             }

I've looked for basic simple examples but they are with Retrofit, GSON, Interfaces, or in Kotlin. Need to understand it codewise.

答案1

得分: 1

以下是您要翻译的内容:

可以使用`addHeader`方法将头信息作为参数发送并添加头信息

Request getRequest = chain.request();
Request.Builder requestBuilder = getRequest.newBuilder()
    .addHeader("Header", "123");
Request request = requestBuilder.build();
return chain.proceed(request);

您还可以访问并查看答案[链接1][1][链接2][2]

以下是您可以使用的所有请求结构

OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(new Interceptor() {
    @Override
    public Response intercept(Interceptor.Chain chain) throws IOException {
        Request original = chain.request();

        Request request = original.newBuilder()
                .method(original.method(), original.body())
                .build();

        return chain.proceed(request);
    }
};
OkHttpClient client = httpClient.build();

Request request = new Request.Builder()
        .url("URL")
        .addHeader("Header", "123")
        .build();

client.newCall(request).enqueue(new Callback() {
    @Override
    public void onFailure(Call call, IOException e) {
        e.printStackTrace();
        Log.d("OKHTTP3", e.getMessage());
        // 您会得到这个失败
        runOnUiThread(() -> {

        });
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        try {
            final String _body = response.body().string();
            Log.d("OKHTTP3", _body);
            runOnUiThread(() -> {

            });
        } catch (InterruptedIOException e) {
            runOnUiThread(() -> {
                // 或者根据超时时间而定的异常

            });
        }
    }
});
[1]: https://stackoverflow.com/questions/32196424/how-to-add-headers-to-okhttp-request-interceptor
[2]: https://stackoverflow.com/questions/45366657/okhttp-adding-headers

请注意,代码部分没有翻译。

英文:

You can use by method addHeader send chain as param and add headers.

 Request getRequest = chain.request();
Request.Builder requestBuilder = getRequest.newBuilder()
.addHeader("Header", "123");
Request request = requestBuilder.build();
return chain.proceed(request);

You can also visit and look at the answers link1 and link2.

Here is the all-request Structure you can use.

OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(new Interceptor() {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request original = chain.request();
Request request = original.newBuilder()
.method(original.method(), original.body())
.build();
return chain.proceed(request);
}
};
OkHttpClient client = httpClient.build();
Request request = new Request.Builder()
.url("URL")
.addHeader("Header", "123")
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
Log.d("OKHTTP3", e.getMessage());
// You get this failure
runOnUiThread(() -> {
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
try {
final String _body = response.body().string();
Log.d("OKHTTP3", _body);
runOnUiThread(() -> {
});
} catch (InterruptedIOException e) {
runOnUiThread(() -> {
// Or this exception depending when timeout is reached
});
}
}
});

答案2

得分: 0

使用addHeader()来添加头部。header()将已添加的头部名称设置为值。

Request newRequest = originalRequest.newBuilder()
    .addHeader("Header", "123")
    .build();

为了验证它是否正常工作,你可以使用HttpLoggingInterceptor来记录你的网络请求。

英文:

Use addHeader() to add headers. header() sets the already added header name to the value.

Request newRequest = originalRequest.newBuilder()
.addHeader("Header", "123")
.build();

And to verify it's working correctly, you can use HttpLoggingInterceptor to log your network requests.

答案3

得分: 0

要检查您的请求并添加标头,您可以使用拦截器。

要添加标头,请使用以下代码(从gist复制):

OkHttpClient.Builder httpClient = new OkHttpClient.Builder();  
httpClient.addInterceptor(new Interceptor() {  
    @Override
    public Response intercept(Interceptor.Chain chain) throws IOException {
        Request original = chain.request();

        Request request = original.newBuilder()
            .header("User-Agent", "Your-App-Name")
            .header("Accept", "application/vnd.yourapi.v1.full+json")
            .method(original.method(), original.body())
            .build();

        return chain.proceed(request);
    }
});

OkHttpClient client = httpClient.build();  
Retrofit retrofit = new Retrofit.Builder()  
    .baseUrl(API_BASE_URL)
    .addConverterFactory(GsonConverterFactory.create())
    .client(client)
    .build();

要查看标头,您可以使用提供的示例代码这里

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

    long t1 = System.nanoTime();
    logger.info(String.format("Sending request %s on %s%n%s",
        request.url(), chain.connection(), request.headers()));

    Response response = chain.proceed(request);

    long t2 = System.nanoTime();
    logger.info(String.format("Received response for %s in %.1fms%n%s",
        response.request().url(), (t2 - t1) / 1e6d, response.headers()));

    return response;
  }
}
英文:

To check your request and to add headers, you can use interceptors.

To add headers, (copied from gist):

OkHttpClient.Builder httpClient = new OkHttpClient.Builder();  
httpClient.addInterceptor(new Interceptor() {  
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request original = chain.request();
Request request = original.newBuilder()
.header("User-Agent", "Your-App-Name")
.header("Accept", "application/vnd.yourapi.v1.full+json")
.method(original.method(), original.body())
.build();
return chain.proceed(request);
}
}
OkHttpClient client = httpClient.build();  
Retrofit retrofit = new Retrofit.Builder()  
.baseUrl(API_BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();

To see your headers, you can use sample example provided here:

class LoggingInterceptor implements Interceptor {
@Override public Response intercept(Interceptor.Chain chain) throws IOException {
Request request = chain.request();
long t1 = System.nanoTime();
logger.info(String.format("Sending request %s on %s%n%s",
request.url(), chain.connection(), request.headers()));
Response response = chain.proceed(request);
long t2 = System.nanoTime();
logger.info(String.format("Received response for %s in %.1fms%n%s",
response.request().url(), (t2 - t1) / 1e6d, response.headers()));
return response;
}
}

huangapple
  • 本文由 发表于 2020年5月30日 22:16:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/62103697.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定