Site icon MobileSiri

Android OkHttp Tutorial

OkHttp is a popular library that reduces the amount of code, OkHttp Android is very easy for you to make use of storage on the web for your app. OkHttp also makes it very easy to connect to the internet using Http. It takes care of connecting to the server. It looks for bad connection issues and recovery for common connection problems. It is an HTTP client that’s efficient by default.

By: Murtaza Ali

OkHttp is necessary for IPv4, IPv6 and for services hosted in redundant data centers. OkHttp supports Android 2.3 and above. Java 1.7 is the minimum requirements for this.
Steps for using OkHttp
1. Adding the library
To add OkHttp in your project follow below steps:
 Download OkHttp jar

Go to file and select project structure a window will pop up. Click on app and then on Dependencies tab as shown below

 Press the plus sign or Alt + Insert and then select library dependency from the pop-up window

 In the search window type as below and select the one com.squareup.okhttp.okhttp:2.2.0 after selection press OK to complete

 Press sync Gradle in cream colored band at the top of window and press ok to close the window

You can confirm that library included successfully to your project by opening the
 build.gradle(app)

Creating a new project Using OkHttp Android library

Goto file create new project
Step 1:
Android Manifest Permission for OkHttp
In android manifest add the two permissions above application tag as shown below

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mobilesiri.okhttp" >
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>

<application
android:allowBackup=”true”
android:icon=”@drawable/ic_launcher”
android:label=”@string/app_name”
android:theme=”@style/AppTheme” >

<activity
android:name=”.MainActivity”
android:label=”@string/app_name” >
<intent-filter>
<action android:name=”android.intent.action.MAIN” />
<category android:name=”android.intent.category.LAUNCHER” />
</intent-filter>

</activity>
<activity
android:name=”.PostActivity”
android:label=”@string/app_name” />
</application>
</manifest>

GET Image From URL Using OkHttp
Step 2:
Add the following code in activity_main.xml file

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<Button
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:id=”@+id/bStart”
android:text=”click to download image through OkHttp”
/>

<TextView  android:layout_width=”wrap_content”

android:layout_height=”wrap_content”
android:id=”@+id/tvBytes”
android:layout_below=”@+id/bStart”
/>

<ImageView
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:id=”@+id/Iview”
android:layout_below=”@+id/tvBytes”/>

<Button
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:id=”@+id/bpost”
android:text=”Post data through OkHttp”
android:layout_alignParentBottom=”true”
/>
</RelativeLayout>

Step 3:
Open MainActivity.java class and add the following code

package com.mobilesiri.okhttp;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

public class MainActivity extends Activity {

Button bstart, bpost;
ImageView imageView;
TextView tv;
private final String url = “http://serviceapi.skholingua.com/images/skholingua_image.png”;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

imageView = (ImageView)findViewById(R.id.Iview);
tv = (TextView) findViewById(R.id.tvBytes);
bstart =(Button) findViewById(R.id.bStart);

bstart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
OkHttpHandler handler = new OkHttpHandler();

byte[] image = new byte[0];
try{
image = handler.execute(url).get();
if (image != null && image.length > 0){
Bitmap bitmap = BitmapFactory.decodeByteArray(image, 0, image.length);
imageView.setImageBitmap(bitmap);
tv.setText(“Total btytes download: “+ image.length);
}
}catch (Exception e){
tv.setText(“sorry, something went wrong!”);
}
}
});
bpost = (Button) findViewById(R.id.bpost);
bpost.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, PostActivity.class);
startActivity(i);
}
});

}
public class OkHttpHandler extends AsyncTask<String, Void, byte[]> {

OkHttpClient client = new OkHttpClient();

@Override
protected byte[] doInBackground(String… params) {

Request.Builder builder = new Request.Builder();
builder.url(params[0]);
Request request = builder.build();

try {
Response response = client.newCall(request).execute();
return response.body().bytes();
}catch (Exception e){
e.printStackTrace();
}
return null;
}
}

}

Step 4:
POST login data to a Server Using OkHttp:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<EditText
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:id=”@+id/etName”
android:ems=”10″  android:hint=”UserName” />
<EditText
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:id=”@+id/etPass”
android:ems=”10″
android:hint=”Password”
android:inputType=”textPassword”
android:layout_below=”@+id/etName” />

<Button
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:id=”@+id/bSend”
android:text=”Send Data”
android:layout_below=”@+id/etPass”
/>

<TextView

android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:id=”@+id/tvpost”
android:layout_below=”@+id/bSend”
/>
</RelativeLayout>

Step 5:
Go to java and add a new java class then add following code

package com.mobilesiri.okhttp;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

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

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

public class PostActivity extends Activity{

TextView output;
Button bsend;
EditText etName, etPass;
final String url = “http://serviceapi.skholingua.com/open-feeds/display_received_params.php”;

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

output = (TextView) findViewById(R.id.tvpost);
etName = (EditText) findViewById(R.id.etName);
etPass = (EditText) findViewById(R.id.etPass);
bsend = (Button) findViewById(R.id.bSend);
bsend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String userName = etName.getText().toString();
String pass = etPass.getText().toString();
OkHttp handler = new OkHttp(userName, pass);
String result = null;
try{
result = handler.execute(url).get();
}catch (ExecutionException e){
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
output.append(result + “n”);
}
});
}
private class OkHttp extends AsyncTask<String, Void, String>{

OkHttpClient client = new OkHttpClient();
String userName, pass;
public OkHttp(String userName, String pass){
this.userName = userName;
this.pass = pass;
}
@Override
protected String doInBackground(String… params) {

RequestBody body = new FormEncodingBuilder()
.add(“name”, userName)
.add(“pass”, pass).build();
Request request = new Request.Builder()
.url(params[0]).post(body).build();
try{
Response response = client.newCall(request).execute();
if (!response.isSuccessful())
throw new IOException(“Unexpected code” + response.toString());
return response.body().string();
}catch (Exception e){
e.printStackTrace();
}
return null;
}
}
}

MobileSiri.com is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to Amazon.com. Read about our Affiliates Disclosure Policy here. Amazon and the Amazon logo are trademarks of Amazon.com, Inc. or its affiliates.
Exit mobile version