1. sylsau's Avatar
    Hello,

    I create that thread to present you a tutorial learning you to use OkHttp to make Network Requests on Android. Note that you can enjoy this tutorial in video on Youtube :



    Created by Square, OkHttp is an open source project designed to be an efficient HTTP and HTTP/2 client. It lets you to make fast requests and save bandwith. It offers some great features out of the box like to share a socket for all HTTP/2 requests to the same host, a connection pooling mechanism when HTTP/2 is not available, transparent GZIP feature to reduce download sizes and a caching mechanism for responses. Besides, OkHttp has a great mechanism to manage common connection problems. And now, it supports also WebSocket.

    OkHttp offers a request / response API that makes developers life easier. It supports synchronous and asynchronous calls. Even better, OkHttp is also available for Java projects with Java 7 as requirement.

    First you need to add the following dependency to your build.gradle file :

    Code:
    compile 'com.squareup.okhttp3:okhttp:3.5.0'
    For our example, we are going to consume a simple JSON Rest Web Service from the SSaurel’s Website : http://www.ssaurel.com/tmp/todos . So, we are going to create a simple layout with a Button to start the network request and a TextView to display the date got from the Web Service :

    Code:
    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:tools="http://schemas.android.com/tools"
      android:id="@+id/activity_main"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:paddingBottom="@dimen/activity_vertical_margin"
      android:paddingLeft="@dimen/activity_horizontal_margin"
      android:paddingRight="@dimen/activity_horizontal_margin"
      android:paddingTop="@dimen/activity_vertical_margin"
      tools:context="com.ssaurel.okhttptut.MainActivity">
    
      <Button
        android:id="@+id/getBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="50dp"
        android:layout_centerHorizontal="true"
        android:text="Get WebService"/>
    
      <TextView
        android:id="@+id/result"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Result ..."
        android:layout_centerHorizontal="true"
        android:textSize="17sp"
        android:layout_below="@id/getBtn"
        android:layout_marginTop="20dp"/>
    
    </RelativeLayout>
    Now, it’s time to write the Java code to make the Network Request by using the OkHttp API. First, we create the OkHttpClient instance. Then, we need to create the request via the Request object and its Builder class. Next step is to pass the request in parameter of the newcall method of the OkHttpClient instance created. OkHttp supports asynchronous and synchronous calls. Here, we are going to use asynchronous request so we call the enqueue method. It takes a Callback object in parameter which has two methods : onFailure and onResponse. Note that these methods are executed in a separate thread. So, if you want to update your User Interface with data got from the Network inside this method, you must embed this in a runOnUiThread call to ensure the update will be made on the UI Thread.

    The Java code to consume the JSON Web Service with OkHttp will have the following form :

    Code:
    package com.ssaurel.okhttptut;
    
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.view.View;
    import android.widget.Button;
    import android.widget.TextView;
    
    import java.io.IOException;
    
    import okhttp3.Call;
    import okhttp3.Callback;
    import okhttp3.OkHttpClient;
    import okhttp3.Request;
    import okhttp3.Response;
    
    public class MainActivity extends AppCompatActivity {
    
      private Button getBtn;
      private TextView result;
      private OkHttpClient client;
    
      @Override
      protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        result = (TextView) findViewById(R.id.result);
        getBtn = (Button) findViewById(R.id.getBtn);
        getBtn.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View view) {
            getWebservice();
          }
        });
    
        client = new OkHttpClient();
      }
    
      private void getWebservice() {
        final Request request = new Request.Builder().url("http://www.ssaurel.com/tmp/todos").build();
        client.newCall(request).enqueue(new Callback() {
          @Override
          public void onFailure(Call call, IOException e) {
            runOnUiThread(new Runnable() {
              @Override
              public void run() {
                result.setText("Failure !");
              }
            });
          }
    
          @Override
          public void onResponse(Call call, final Response response) {
            runOnUiThread(new Runnable() {
              @Override
              public void run() {
                try {
                  result.setText(response.body().string());
                } catch (IOException ioe) {
                  result.setText("Error during get body");
                }
              }
            });
          }
       });
      }
    }
    Now, you can try your application and you should obtain the following result by clicking on the Get WebService button :



    Don't hesitate to give it a try to this tutorial and give me your feedbacks.

    Thanks.

    Sylvain
    01-16-2017 04:34 AM
  2. B. Diddy's Avatar
    Thanks for the tutorial!
    01-16-2017 10:01 PM

Similar Threads

  1. Should I factory reset my phone to start camera application?
    By AC Question in forum Ask a Question
    Replies: 2
    Last Post: 01-18-2017, 11:51 PM
  2. screen turns on
    By Barbara Thomas1 in forum Samsung Galaxy Note 5
    Replies: 3
    Last Post: 01-16-2017, 01:35 AM
  3. HOW do I locate the Clip Tray on my Cell Phone???
    By AC Question in forum Ask a Question
    Replies: 1
    Last Post: 01-14-2017, 08:31 AM
  4. When will be the last Update Google will do to the Lg g4?
    By AC Question in forum Ask a Question
    Replies: 1
    Last Post: 01-14-2017, 02:19 AM
  5. Why won't snapchat pics and videos save on my HTC 10?
    By tomdzz in forum Ask a Question
    Replies: 0
    Last Post: 01-14-2017, 02:02 AM

Tags for this Thread

LINK TO POST COPIED TO CLIPBOARD