OkHttp – How to send HTTP requests

OkHttp logo

This article shows you how to use the OkHttp library to send an HTTP GET/POST requests and some frequent used examples.

P.S Tested with OkHttp 4.2.2

pom.xml

	<dependency>
	  <groupId>com.squareup.okhttp3</groupId>
	  <artifactId>okhttp</artifactId>
	  <version>4.2.2</version>
	</dependency>

1. Synchronous Get Request

OkHttpExample1.java

package com.mkyong.http;

import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;

public class OkHttpExample1 {

    // only one client, singleton, better puts it in a factory, 
	// multiple instances will create more memory.
    private final OkHttpClient httpClient = new OkHttpClient();

    public static void main(String[] args) throws IOException {
        OkHttpExample1 obj = new OkHttpExample1();
        obj.sendGETSync();
    }

    private void sendGETSync() throws IOException {

        Request request = new Request.Builder()
                .url("https://httpbin.org/get")
                .addHeader("custom-key", "mkyong")  // add request headers
                .addHeader("User-Agent", "OkHttp Bot")
                .build();

        try (Response response = httpClient.newCall(request).execute()) {

            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

            // Get response headers
            Headers responseHeaders = response.headers();
            for (int i = 0; i < responseHeaders.size(); i++) {
                System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
            }

            // Get response body
            System.out.println(response.body().string());
        }

    }

}

2. Asynchronous Get Request

OkHttpExample2.java

package com.mkyong.okhttp;

import okhttp3.*;
import java.io.IOException;

public class OkHttpExample2 {

    // only one client
    private final OkHttpClient httpClient = new OkHttpClient();

    public static void main(String[] args) throws IOException {
        OkHttpExample2 obj = new OkHttpExample2();
        obj.sendGET();
    }

    private void sendGET() throws IOException {

        Request request = new Request.Builder()
                .url("https://httpbin.org/get")
                .addHeader("custom-key", "mkyong")  // add request headers
                .addHeader("User-Agent", "OkHttp Bot")
                .build();

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

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try (ResponseBody responseBody = response.body()) {
                    if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

                    // Get response headers
                    Headers responseHeaders = response.headers();
                    for (int i = 0, size = responseHeaders.size(); i < size; i++) {
                        System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
                    }

                    // Get response body
                    System.out.println(responseBody.string());
                }
            }
        });

    }

}

3. POST Request - Form Parameters

3.1 Add from parameters in RequestBody

OkHttpExample3.java

package com.mkyong.http;

import okhttp3.*;

import java.io.IOException;

public class OkHttpExample3 {

    private final OkHttpClient httpClient = new OkHttpClient();

    public static void main(String[] args) throws IOException {
        OkHttpExample3 obj = new OkHttpExample3();
        obj.sendPOST();
    }

    private void sendPOST() throws IOException {

        // form parameters
        RequestBody formBody = new FormBody.Builder()
                .add("username", "abc")
                .add("password", "123")
                .add("custom", "secret")
                .build();

        Request request = new Request.Builder()
                .url("https://httpbin.org/post")
                .addHeader("User-Agent", "OkHttp Bot")
                .post(formBody)
                .build();

        try (Response response = httpClient.newCall(request).execute()) {

            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

            // Get response body
            System.out.println(response.body().string());
        }

    }

}

4. POST Request - JSON

4.1 Create a JSON RequestBody manually.

OkHttpExample4.java

package com.mkyong.http;

import okhttp3.*;

import java.io.IOException;

public class OkHttpExample4 {

    private final OkHttpClient httpClient = new OkHttpClient();

    public static void main(String[] args) throws IOException {
        OkHttpExample4 obj = new OkHttpExample4();
        obj.sendPOST();
    }

    private void sendPOST() throws IOException {

        // json formatted data
        String json = new StringBuilder()
                .append("{")
                .append("\"name\":\"mkyong\",")
                .append("\"notes\":\"hello\"")
                .append("}").toString();

		// json request body
        RequestBody body = RequestBody.create(
                json,
                MediaType.parse("application/json; charset=utf-8")
        );

        Request request = new Request.Builder()
                .url("https://httpbin.org/post")
                .addHeader("User-Agent", "OkHttp Bot")
                .post(body)
                .build();

        try (Response response = httpClient.newCall(request).execute()) {

            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

            // Get response body
            System.out.println(response.body().string());
        }

    }

}

5. Authentication

Start a simple Spring Security WebApp providing HTTP basic authentication, and test it with the OkHttp library.

5.1 Header authentication at Request directly.


	Request request = new Request.Builder()
		.url("http://localhost:8080/books")
		.addHeader("Authorization", Credentials.basic("user", "password"))
		.build();
				

5.2 Create an Authenticator, more flexible to handle authentication.


	private final Authenticator authenticator = new Authenticator() {
        @Override
        public Request authenticate(Route route, Response response) throws IOException {
            if (response.request().header("Authorization") != null) {
                return null; // Give up, we've already attempted to authenticate.
            }

            System.out.println("Authenticating for response: " + response);
            System.out.println("Challenges: " + response.challenges());
            String credential = Credentials.basic("user", "password");
            return response.request().newBuilder()
                    .header("Authorization", credential)
                    .build();
        }
    };

    private final OkHttpClient httpClient = new OkHttpClient
		.Builder()
		.authenticator(authenticator)
		.build();

6. FAQs

6.1 Disabled Redirect.

HttpClientExample5_1.java

	private final OkHttpClient httpClient = new OkHttpClient.Builder()
            .followRedirects(false)
            .build();

6.2 Timeout, 5 seconds.


	private final OkHttpClient httpClient = new OkHttpClient.Builder()
            .connectTimeout(5, TimeUnit.SECONDS)
            .writeTimeout(5, TimeUnit.SECONDS)
            .readTimeout(5, TimeUnit.SECONDS)
            .build();
Note
More OkHttp Recipes

References

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar