Android HttpUrlConnection Get and Post Request Tutorial

Total Views : 3,655
Zoom In Zoom Out Read Later Print

We will create a connection between Android App and server using httpurlconnection in AsyncTask, then send or receive the data request from Android App to server.


In this tutorial we will learn about making get and post request using HttpUrlConnection. for a get request parameters encoded with URL but in post request the data sent to the server is stored in the request body of the HTTP request.

Creating Asynchronous Class

We will create a Asynchronous class called as RequestAsync in MainActivity.java file. Asynchronous class operates independently of other processes. It will execute the process in background.

PostAsync

public class RequestAsync extends AsyncTask<String,String,String> {
@Override
protected String doInBackground(String... strings) {
return null;
}

@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}

Encode parameters

We need to convert JSON object into URL parameters first.

encodeParams()

private static String encodeParams(JSONObject params) throws Exception {
StringBuilder result = new StringBuilder();
boolean first = true;
Iterator<String> itr = params.keys();
while(itr.hasNext()){
String key= itr.next();
Object value = params.get(key);
if (first)
first = false;
else
result.append("&");

result.append(URLEncoder.encode(key, "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(value.toString(), "UTF-8"));
}
return result.toString();
}

Make get request

GET Request

public static String sendGet(String url) throws IOException {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
int responseCode = con.getResponseCode();
System.out.println("Response Code :: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { // connection ok
BufferedReader in = new BufferedReader(new InputStreamReader( con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();

while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
} else {
return "";
}
}

Make post request

POST Request

public static String sendPost(String r_url , JSONObject postDataParams) throws Exception {
URL url = new URL(r_url);

HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(20000);
conn.setConnectTimeout(20000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);

OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(os, "UTF-8"));
writer.write(encodeParams(postDataParams));
writer.flush();
writer.close();
os.close();

int responseCode=conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {

BufferedReader in=new BufferedReader( new InputStreamReader(conn.getInputStream()));
StringBuffer sb = new StringBuffer("");
String line="";
while((line = in.readLine()) != null) {
sb.append(line);
break;
}
in.close();
return sb.toString();
}
return null;
}

Reading Response

Request Response

int responseCode=conn.getResponseCode(); // To Check for 200
if (responseCode == HttpsURLConnection.HTTP_OK) {

BufferedReader in=new BufferedReader( new InputStreamReader(conn.getInputStream()));
StringBuffer sb = new StringBuffer("");
String line="";
while((line = in.readLine()) != null) {
sb.append(line);
break;
}
in.close();
return sb.toString();
}

Complete Class

RequestHandler.java

package com.prodevsblog.httptest;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Iterator;

import javax.net.ssl.HttpsURLConnection;

public class RequestHandler {
public static String sendPost(String r_url , JSONObject postDataParams) throws Exception {
URL url = new URL(r_url);

HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(20000);
conn.setConnectTimeout(20000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);

OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(os, "UTF-8"));
writer.write(encodeParams(postDataParams));
writer.flush();
writer.close();
os.close();

int responseCode=conn.getResponseCode(); // To Check for 200
if (responseCode == HttpsURLConnection.HTTP_OK) {

BufferedReader in=new BufferedReader( new InputStreamReader(conn.getInputStream()));
StringBuffer sb = new StringBuffer("");
String line="";
while((line = in.readLine()) != null) {
sb.append(line);
break;
}
in.close();
return sb.toString();
}
return null;
}
public static String sendGet(String url) throws IOException {
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
int responseCode = con.getResponseCode();
System.out.println("Response Code :: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { // connection ok
BufferedReader in = new BufferedReader(new InputStreamReader( con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();

while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
} else {
return "";
}
}
private static String encodeParams(JSONObject params) throws Exception {
StringBuilder result = new StringBuilder();
boolean first = true;
Iterator<String> itr = params.keys();
while(itr.hasNext()){
String key= itr.next();
Object value = params.get(key);
if (first)
first = false;
else
result.append("&");

result.append(URLEncoder.encode(key, "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(value.toString(), "UTF-8"));
}
return result.toString();
}
}

Code of MainActivity

MainActivity.java

package com.prodevsblog.httptest;

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

import org.json.JSONObject;


public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new RequestAsync().execute();
}
public class RequestAsync extends AsyncTask<String,String,String> {
@Override
protected String doInBackground(String... strings) {
try {
//GET Request
//return RequestHandler.sendGet("https://prodevsblog.com/android_get.php");

// POST Request
JSONObject postDataParams = new JSONObject();
postDataParams.put("name", "Manjeet");
postDataParams.put("email", "manjeet@gmail.com");
postDataParams.put("phone", "+1111111111");

return RequestHandler.sendPost("https://prodevsblog.com/android_post.php",postDataParams);
}
catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}

@Override
protected void onPostExecute(String s) {
if(s!=null){
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG).show();
}
}


}
}

PHP Code

android_get.php

<?php
echo "Hello";
?>

android_post.php

<?php
echo json_encode($_POST);
?>

See More

Latest Photos