Home Tutorials Training Consulting Products Books Company Donate Contact us









Online training

Events

Quick links

Share

Lars Vogel (c) 2014, 2016 vogella GmbH Version 2.6, 25.06.2016

This tutorial explains the usage and purpose of the HTTP and HTTPS library OkHttp.

1. Using OkHttp for efficient network access

1.1. What is OkHTTP?

OkHTTP is an open source project designed to be an efficient HTTP client. It supports the SPDY protocol. SPDY is the basis for HTTP 2.0 and allows multiple HTTP requests to be multiplexed over one socket connection.

If you are using Maven or Gradle as build system you can simply add a dependency to group ID com.squareup.okhttp, artifactId, okhttp and the version 2.5.0 (current as of this writing).

compile 'com.squareup.okhttp:okhttp:2.5.0'

As of Android 5.0, OkHttp is part of the Android platform and is used for all HTTP calls.

1.2. Creating request objects for make network calls

To use OkHttp you need to create a Request object.

// avoid creating several instances, should be singleon
OkHttpClient client = new OkHttpClient();

Request request = new Request.Builder()
                     .url("http://www.vogella.com/index.html")
                     .build();

You can also add parameters

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

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

You can also add authentication headers

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

1.3. Sending and receiving network calls

To make a synchronous network call, use the Client to create a Call object and use the execute method.

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

To make asynchronous calls, also create a Call object but use the enqueue method.

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 {
        // do something wih the result
    }
}

Note: If you are using Android and want to update the UI, you need to use Content.runOnUiThread(new Runnable) to sync with the UI thread.

2. Exercise: Using OkHttp

This is an example for the usage of OkHttp in a standard Java program, but this library can also be used in Android applications. This example demonstrates the usage of the API. Create a new Java project called com.vogella.java.library.okhttp.

Add OkHttp them to the build path of your project via your Maven or Gradle build. Afterwards create the following test class which is more or less taken for the http://square.github.io/okhttp/ website.

package com.vogella.java.library.okhttp;


import java.io.IOException;

import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

    public class TestMain {
      OkHttpClient client = new OkHttpClient();
      // code request code here
      String doGetRequest(String url) throws IOException {
        Request request = new Request.Builder()
            .url(url)
            .build();

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

      // post request code here

      public static final MediaType JSON
      = MediaType.parse("application/json; charset=utf-8");

      // test data
      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}"
                + "]}";
          }

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

      public static void main(String[] args) throws IOException {

        // issue the Get request
        TestMain example = new TestMain();
        String getResponse = example.doGetRequest("http://www.vogella.com");
        System.out.println(getResponse);


        // issue the post request

        String json = example.bowlingJson("Jesse", "Jake");
        String postResponse = example.doPostRequest("http://www.roundsapp.com/post", json);
        System.out.println(postResponse);
      }
    }

3. vogella training and consulting support

Copyright © 2012-2018 vogella GmbH. Free use of the software examples is granted under the terms of the Eclipse Public License 2.0. This tutorial is published under the Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Germany license.