Hi Guys, Welcome to Proto Coders Point, In this Android Tutorial we gonna have a look on how to get response from server using OkHttp android library.

Note: This Android tutorial is kept simple for http request with okhttp library,

This is PART 1 – Here we will just fetch the data from server which is in json format and show data in Android TextView

Final Result of PART 1

okhttp android library screenshot example

What is OkHttp Library?

HTTP is the latest way to network in application. Now a days all data such as text,images or media are been exchange using HTTP CALLS.

Using OKHTTP will make our application stuff load content faster and saves lots of bandwidth.

Okhttp android library makes it simple to make any asynchronous HTTP request.

Using okhttp is quite very simple to get request/response API, It Supports both synchronous and asynchronous callls with callbacks.

Adding the library in our android project

implementation("com.squareup.okhttp3:okhttp:4.4.0")  // add this line in gradle.build(app level)

Check out the latest version of okhttp library in official website 

Internet permission

as we are making network called to fetch data from server we need to assign INTERNET permission

<uses-permission android:name="android.permission.INTERNET"/>

So to so open AndroidManifest.xml file and the <user-permissioon> Internet.

Snippet code to GET data from URL

OkHttpClient client = new OkHttpClient();  
        String url = "your api link here";

        Request request = new Request.Builder()
                .url(url)   //request for url by passing url
                .build();

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

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                if(response.isSuccessful())
                {
                   // task after data is received 
                }
            }
        });

OkHttp will perform best when simple OkHttpClient instance is been created and reused it  in program when every needed to make HTTP Calls, This is best each client is given to hold its own  connection so this makes the task smooth, fast and easy to load data from server side.

Complete Source Code to make Http Request using OkHttp android library – Part 1

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textview1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

This have only one widget(textview) where are gonna show the date response for server

MainActivity.java

package com.protocoderspoint.androidokhttp;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.TextView;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        textView = (TextView)findViewById(R.id.textview1);

        OkHttpClient client = new OkHttpClient();
        String url = "https://protocoderspoint.com/jsondata/superheros.json";

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

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

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                if(response.isSuccessful())
                {
                    final String myResponse = response.body().string();
                    MainActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            textView.setText(myResponse);                // runOnUiThread is used because A Thread is current used by OkHttp Thread
                        }
                    });
                }
            }
        });
    }
}

 

 

 

1 Comment