0

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.

SO 80
  • 197
  • 2
  • 11

3 Answers3

1

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

                    });
                }
            }
        });
Tanveer Munir
  • 1,956
  • 1
  • 12
  • 27
0

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.

Saurabh Thorat
  • 18,131
  • 5
  • 53
  • 70
0

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;
  }
}
Anon
  • 2,608
  • 6
  • 26
  • 38