Okhttp 拦截器问题

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

Okhttp Interceptor issue

问题

  1. 我正在尝试为一个简单的okhttpGet请求添加一个头部如何正确添加HttpHeader我可以进行调试以确保我的头部实际上被发送到服务器吗
  2. Request request = new Request.Builder()
  3. .url("URL")
  4. .build();
  5. OkHttpClient okHttpClient = new OkHttpClient.Builder()
  6. .addInterceptor(new Interceptor() {
  7. @Override
  8. public okhttp3.Response intercept(Chain chain) throws IOException {
  9. Request originalRequest = chain.request();
  10. Request newRequest = originalRequest.newBuilder()
  11. .addHeader("Header", "123")
  12. .build();
  13. return chain.proceed(newRequest);
  14. }
  15. })
  16. .build();
  17. okHttpClient.newCall(request).enqueue(new Callback() {
  18. @Override
  19. public void onFailure(Call call, IOException e) {
  20. }
  21. });

我已经寻找了基本的简单示例,但它们都是关于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?

  1. Request request = new Request.Builder()
  2. .url("URL")
  3. .build();
  4. OkHttpClient okHttpClient = new OkHttpClient.Builder()
  5. .addInterceptor(new Interceptor() {
  6. @Override
  7. public okhttp3.Response intercept(Chain chain) throws IOException {
  8. Request originalRequest = chain.request();
  9. Request newRequest = originalRequest.newBuilder()
  10. .addHeader("Header", "123")
  11. .build();
  12. return chain.proceed(newRequest);
  13. }
  14. })
  15. .build();
  16. okHttpClient.newCall(request).enqueue(new Callback() {
  17. @Override
  18. public void onFailure(Call call, IOException e) {
  19. }

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

答案1

得分: 1

以下是您要翻译的内容:

  1. 可以使用`addHeader`方法将头信息作为参数发送并添加头信息
  2. Request getRequest = chain.request();
  3. Request.Builder requestBuilder = getRequest.newBuilder()
  4. .addHeader("Header", "123");
  5. Request request = requestBuilder.build();
  6. return chain.proceed(request);
  7. 您还可以访问并查看答案[链接1][1][链接2][2]
  8. 以下是您可以使用的所有请求结构
  9. OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
  10. httpClient.addInterceptor(new Interceptor() {
  11. @Override
  12. public Response intercept(Interceptor.Chain chain) throws IOException {
  13. Request original = chain.request();
  14. Request request = original.newBuilder()
  15. .method(original.method(), original.body())
  16. .build();
  17. return chain.proceed(request);
  18. }
  19. };
  20. OkHttpClient client = httpClient.build();
  21. Request request = new Request.Builder()
  22. .url("URL")
  23. .addHeader("Header", "123")
  24. .build();
  25. client.newCall(request).enqueue(new Callback() {
  26. @Override
  27. public void onFailure(Call call, IOException e) {
  28. e.printStackTrace();
  29. Log.d("OKHTTP3", e.getMessage());
  30. // 您会得到这个失败
  31. runOnUiThread(() -> {
  32. });
  33. }
  34. @Override
  35. public void onResponse(Call call, Response response) throws IOException {
  36. try {
  37. final String _body = response.body().string();
  38. Log.d("OKHTTP3", _body);
  39. runOnUiThread(() -> {
  40. });
  41. } catch (InterruptedIOException e) {
  42. runOnUiThread(() -> {
  43. // 或者根据超时时间而定的异常
  44. });
  45. }
  46. }
  47. });
  48. [1]: https://stackoverflow.com/questions/32196424/how-to-add-headers-to-okhttp-request-interceptor
  49. [2]: https://stackoverflow.com/questions/45366657/okhttp-adding-headers

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

英文:

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

  1. Request getRequest = chain.request();
  2. Request.Builder requestBuilder = getRequest.newBuilder()
  3. .addHeader("Header", "123");
  4. Request request = requestBuilder.build();
  5. 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.

  1. OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
  2. httpClient.addInterceptor(new Interceptor() {
  3. @Override
  4. public Response intercept(Interceptor.Chain chain) throws IOException {
  5. Request original = chain.request();
  6. Request request = original.newBuilder()
  7. .method(original.method(), original.body())
  8. .build();
  9. return chain.proceed(request);
  10. }
  11. };
  12. OkHttpClient client = httpClient.build();
  13. Request request = new Request.Builder()
  14. .url("URL")
  15. .addHeader("Header", "123")
  16. .build();
  17. client.newCall(request).enqueue(new Callback() {
  18. @Override
  19. public void onFailure(Call call, IOException e) {
  20. e.printStackTrace();
  21. Log.d("OKHTTP3", e.getMessage());
  22. // You get this failure
  23. runOnUiThread(() -> {
  24. });
  25. }
  26. @Override
  27. public void onResponse(Call call, Response response) throws IOException {
  28. try {
  29. final String _body = response.body().string();
  30. Log.d("OKHTTP3", _body);
  31. runOnUiThread(() -> {
  32. });
  33. } catch (InterruptedIOException e) {
  34. runOnUiThread(() -> {
  35. // Or this exception depending when timeout is reached
  36. });
  37. }
  38. }
  39. });

答案2

得分: 0

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

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

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

英文:

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

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

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

答案3

得分: 0

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

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

  1. OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
  2. httpClient.addInterceptor(new Interceptor() {
  3. @Override
  4. public Response intercept(Interceptor.Chain chain) throws IOException {
  5. Request original = chain.request();
  6. Request request = original.newBuilder()
  7. .header("User-Agent", "Your-App-Name")
  8. .header("Accept", "application/vnd.yourapi.v1.full+json")
  9. .method(original.method(), original.body())
  10. .build();
  11. return chain.proceed(request);
  12. }
  13. });
  14. OkHttpClient client = httpClient.build();
  15. Retrofit retrofit = new Retrofit.Builder()
  16. .baseUrl(API_BASE_URL)
  17. .addConverterFactory(GsonConverterFactory.create())
  18. .client(client)
  19. .build();

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

  1. class LoggingInterceptor implements Interceptor {
  2. @Override public Response intercept(Interceptor.Chain chain) throws IOException {
  3. Request request = chain.request();
  4. long t1 = System.nanoTime();
  5. logger.info(String.format("Sending request %s on %s%n%s",
  6. request.url(), chain.connection(), request.headers()));
  7. Response response = chain.proceed(request);
  8. long t2 = System.nanoTime();
  9. logger.info(String.format("Received response for %s in %.1fms%n%s",
  10. response.request().url(), (t2 - t1) / 1e6d, response.headers()));
  11. return response;
  12. }
  13. }
英文:

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

To add headers, (copied from gist):

  1. OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
  2. httpClient.addInterceptor(new Interceptor() {
  3. @Override
  4. public Response intercept(Interceptor.Chain chain) throws IOException {
  5. Request original = chain.request();
  6. Request request = original.newBuilder()
  7. .header("User-Agent", "Your-App-Name")
  8. .header("Accept", "application/vnd.yourapi.v1.full+json")
  9. .method(original.method(), original.body())
  10. .build();
  11. return chain.proceed(request);
  12. }
  13. }
  14. OkHttpClient client = httpClient.build();
  15. Retrofit retrofit = new Retrofit.Builder()
  16. .baseUrl(API_BASE_URL)
  17. .addConverterFactory(GsonConverterFactory.create())
  18. .client(client)
  19. .build();

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

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

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:

确定