OkHttp GET request with parameters and POST request Tutorial Example

OkHTTP (OkHTTP3) is an open source project designed to be an efficient HTTP client. It’s fully functional tutorial for OkHttp GET and POST Request with parameters and headers.

OkHttp is an HTTP client that’s efficient by default:

  • HTTP/2 support allows all requests to the same host to share a socket.
  • Connection pooling reduces request latency (if HTTP/2 isn’t available).
  • Transparent GZIP shrinks download sizes.
  • Response caching avoids the network completely for repeat requests.

In this tutorial we will be exploring OkHttp Open source library with sample code.

Maven Dependency for OkHttp

OkHttp is available at Maven Central

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

Creating OkHttpClient and Request Object

Best practice to create OkHttp object to make it singleton, In other words avoid creating several instances.

OkHttpClient client = new OkHttpClient();

Request request = new Request.Builder()
                     .url("https://codedaily.in/")
                     .build();

OkHttp GET request with parameters

HttpUrl.Builder urlBuilder = HttpUrl.parse("https://api.github.help").newBuilder();
urlBuilder.addQueryParameter("v", "1.0");
urlBuilder.addQueryParameter("user", "codedaily");
String url = urlBuilder.build().toString();

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

OkHttp GET request with headers

Request request = new Request.Builder()
    .header("Authorization", "your token")
    .url("https://api.github.com/users/deepanshujain92")
    .build();

Sending request and receiving the response

Synchronous request network call

Response response = client.newCall(request).execute();

Asynchronous request network call

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

    @Override
    public void onResponse(Call call, final Response response) throws  IOException {
        if (!response.isSuccessful()) {
            throw new IOException("Unexpected code " + response);
        } else {
        	System.out.println(response.body().string());
    }
}
Advertisement

OkHttp GET Request Full Code

This source code has been taken from OkHttp Official website

package okhttp3.guide;

import java.io.IOException;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class GetExample {
  OkHttpClient client = new OkHttpClient();

  String run(String url) throws IOException {
    Request request = new Request.Builder()
        .url(url)
        .build();

    try (Response response = client.newCall(request).execute()) {
      return response.body().string();
    }
  }

  public static void main(String[] args) throws IOException {
    GetExample example = new GetExample();
    String response = example.run("https://raw.github.com/square/okhttp/master/README.md");
    System.out.println(response);
  }
}

OkHttp POST Request Full Code

This source code has been taken from OkHttp Official website

package okhttp3.guide;

import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class PostExample {
  public static final MediaType JSON = MediaType.get("application/json; charset=utf-8");

  OkHttpClient client = new OkHttpClient();

  String post(String url, String json) throws IOException {
    RequestBody body = RequestBody.create(json, JSON);
    Request request = new Request.Builder()
        .url(url)
        .post(body)
        .build();
    try (Response response = client.newCall(request).execute()) {
      return response.body().string();
    }
  }

  String bowlingJson(String player1, String player2) {
    return "{'winCondition':'HIGH_SCORE',"
        + "'name':'Bowling',"
        + "'round':4,"
        + "'lastSaved':1367702411696,"
        + "'dateStarted':1367702378785,"
        + "'players':["
        + "{'name':'" + player1 + "','history':[10,8,6,7,8],'color':-13388315,'total':39},"
        + "{'name':'" + player2 + "','history':[6,10,5,10,10],'color':-48060,'total':41}"
        + "]}";
  }

  public static void main(String[] args) throws IOException {
    PostExample example = new PostExample();
    String json = example.bowlingJson("Jesse", "Jake");
    String response = example.post("http://www.roundsapp.com/post", json);
    System.out.println(response);
  }
}

HTTPS Request with OkHttp

By default, OkHttp will attempt a MODERN_TLS connection. However, by configuring the client connection Specs you can allow a fall back to COMPATIBLE_TLS connection if the modern configuration fails.

Check this post

Advertisement

Leave a Reply

Your email address will not be published. Required fields are marked *

sixteen − two =