Cara menggunakan OkHTTP di android studio

Bismillaahirrohmaanirrohiim…

Kali ini, saya ingin membuat tutorial sederhana cara mudah menggunakan OkHTTP di android studio.

OkHTTP merupakan library yang digunakan di android studio untuk melakukan request ke suatu URL.
Jika menggunakan PHP, kita bisa pakai PHP CURL. Di javascript, kita bisa pakai ajax.

kenapa memilih OkHTTP, padahal banyak sekali library semacamnya, seperti volley, retrofit, loopj, dll.

Ini masalah selera, namun saya sendiri merasakan kalau OkHTTP terasa lebih stabil, lebih ringan, dan lebih mudah dibandingkan dengan yang lain.

Pada contoh kali ini, kita akan membuat request dengan metode synchronous dan asynchronous.

Sederhananya, request synchronous dijalankan di program dan tidak akan menjalankan kode setelahnya sebelum request telah selesai.
Sebaliknya, request asynchronous dijalankan di background, sehingga kode setelahnya akan langsung dieksekusi tanpa menunggu request selesai.

Masing-masing metode mempunyai kelebihan dan kekurangan, kita boleh pakai sesuai kebutuhan.

Oke langsung saja, pertama buat project baru di android studio

Isikan nama “Belajar OkHTTP” lalu next
Pilih minimum SDK API 17, Android 4.2 Jelly bean ato versi berapa aja sesuai keinginan, lalu next
Pilih empty activity lalu next
Biarkan nilai default “MainActivity” lalu finish
Tunggu sampai selesai menyiapkan project untuk kita.

Buka file build.gradle (Module: app)

Tambahkan kode dibawah ini dibagian dependencies

implementation 'com.squareup.okhttp3:okhttp:3.11.0'

Sehingga hasilnya kurang lebih seperti dibawah ini

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'com.squareup.okhttp3:okhttp:3.11.0'
}

Kemudian klik “Sync Now” ada di link kanan atas. Tunggu sampai selesai sinkronisasinya.

Tambahkan kode permission dibawah ini di AndroidManifest.xml

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

Edit activity_main.xml seperti dibawah ini

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Belajar OkHTTP"
        android:textAlignment="center"
        android:textSize="24sp" />

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_marginBottom="5dp"
        android:background="#c0c0c0" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/buttonSync"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:minHeight="0dp"
            android:minWidth="0dp"
            android:text="Synchronous" />

        <Button
            android:id="@+id/buttonAsync"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:minHeight="0dp"
            android:minWidth="0dp"
            android:text="Asynchronous" />


    </LinearLayout>


</LinearLayout>

Edit file MainActivity.java seperti di bawah ini

package com.rasupe.belajarokhttp;

import android.content.Context;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

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

public class MainActivity extends AppCompatActivity {
    private Button buttonSync, buttonAsync;
    private Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        context = getApplicationContext();

        buttonSync = findViewById(R.id.buttonSync);
        buttonAsync = findViewById(R.id.buttonAsync);

        buttonSync.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                requestSync();
            }
        });
        buttonAsync.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                requestAsync();
            }
        });
    }

    private void requestSync() {
        int SDK_INT = android.os.Build.VERSION.SDK_INT;
        if (SDK_INT > 8) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                    .permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(5, TimeUnit.SECONDS);
        builder.readTimeout(5, TimeUnit.SECONDS);
        builder.writeTimeout(5, TimeUnit.SECONDS);
        OkHttpClient client = builder.build();

        Request request = new Request.Builder()
                //.url("https://publicobject.com/helloworld.txt")
                .url("https://jsonplaceholder.typicode.com/todos/1")
                .build();

        try {
            Response response = client.newCall(request).execute();
            //response.body().string() tidak boleh dipanggil 2x
            String responseString = response.body().string();

            Toast.makeText(this, responseString, Toast.LENGTH_SHORT).show();

        } catch (IOException e) {
            Toast.makeText(this, "Error: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }

        Toast.makeText(this, "OkHTTP requestSync", Toast.LENGTH_SHORT).show();

    }

    private void requestAsync() {
        int SDK_INT = android.os.Build.VERSION.SDK_INT;
        if (SDK_INT > 8) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                    .permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(5, TimeUnit.SECONDS);
        builder.readTimeout(5, TimeUnit.SECONDS);
        builder.writeTimeout(5, TimeUnit.SECONDS);
        OkHttpClient client = builder.build();

        Request request = new Request.Builder()
                //.url("https://publicobject.com/helloworld.txt")
                .url("https://jsonplaceholder.typicode.com/todos/1")
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("debuging", "Request Failed."+e.getMessage());
                responseAsync("Request Failed."+e.getMessage());
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                try {
                    if (response.isSuccessful()) {
                        String responseString = response.body().string();

                        Log.d("debuging", responseString);
                        responseAsync(responseString);
                    } else {
                        Log.d("debuging", "Error "+ response);
                        responseAsync("Error "+ response);
                    }
                } catch (IOException e) {
                    Log.d("debuging", "Exception caught : ", e);
                    responseAsync("Error "+ e.getMessage());
                }
            }
        });
        Toast.makeText(this, "OkHTTP requestAsync", Toast.LENGTH_SHORT).show();

    }

    private void responseAsync(final String responseStr) {
        runOnUiThread(new Runnable() {
            public void run() {
                Toast.makeText(getApplicationContext(), responseStr, Toast.LENGTH_SHORT).show();
            }
        });
    }
}

 

Silahkan di run

semoga tidak error 🙂

Nah, cukup mudah bukan, cara menggunakan OkHTTP di android studio.

Jika ingin request menambahkan header dan metode POST dengan OkHTTP cukup mudah, perhatikan kode dibawah ini:

RequestBody requestBody = new FormBody.Builder()
        .add("param1", "value1")
        .add("param2", "value2")
        .build();

Request request = new Request.Builder()
        //.url("https://publicobject.com/helloworld.txt")
        .url("https://jsonplaceholder.typicode.com/todos/1")
        .post(requestBody)
        .addHeader("Connection", "Keep-Alive")
        .addHeader("Content-Type", "application/x-www-form-urlencoded")
        .build();

Demikian tutorial menggunakan OkHTTP di android studio dengan mudah.

Jika ada yang ingin disampaikan, silahkan tinggalkan di kolom komentar.

Terimakasih

Leave a Reply

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