In most of the android applications it is essential that app may need to connect to internet and make some HTTP requests. In this article i’ll be demonstrating about making simple HTTP Requests in android.

Below are the code snippets to handle HTTP requests.

Download Code

Creating HTTP Client and HTTP Post

// Creating HTTP client
HttpClient httpClient = new DefaultHttpClient();

// Creating HTTP Post
HttpPost httpPost = new HttpPost("http://www.example.com/login");

 

Bulding Post Parameters

The following code will create post parameters pair with key and value.

// Building post parameters, key and value pair
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
nameValuePair.add(new BasicNameValuePair("email", "user@gmail.com"));
nameValuePair.add(new BasicNameValuePair("password", "encrypted_password"));

 

URL Encoding POST data

Before making HTTP request you need to encode the post data in order to convert all string data into valid url format.

// Url Encoding the POST parameters
try {
	httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
}
catch (UnsupportedEncodingException e) {
	// writing error to Log
	e.printStackTrace();
}

 

Finally making HTTP Request

Finally you need to execute httpPost using the httpClient created before.

// Making HTTP Request
try {
	HttpResponse response = httpClient.execute(httpPost);

	// writing response to log
	Log.d("Http Response:", response.toString());

} catch (ClientProtocolException e) {
	// writing exception to log
	e.printStackTrace();
		
} catch (IOException e) {
	// writing exception to log
	e.printStackTrace();
}

 

Final Code

The following is the final code to make http Requests. I am writing response to log. Check your Log report in Eclipse to see your http response.

package com.androidhive.httprequests;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

public class AndroidHTTPRequestsActivity extends Activity {
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		// Creating HTTP client
		HttpClient httpClient = new DefaultHttpClient();
		// Creating HTTP Post
		HttpPost httpPost = new HttpPost(
				"http://www.example.com/login");

		// Building post parameters
		// key and value pair
		List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
		nameValuePair.add(new BasicNameValuePair("email", "user@gmail.com"));
		nameValuePair.add(new BasicNameValuePair("message",
				"Hi, trying Android HTTP post!"));

		// Url Encoding the POST parameters
		try {
			httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
		} catch (UnsupportedEncodingException e) {
			// writing error to Log
			e.printStackTrace();
		}

		// Making HTTP Request
		try {
			HttpResponse response = httpClient.execute(httpPost);

			// writing response to log
			Log.d("Http Response:", response.toString());
		} catch (ClientProtocolException e) {
			// writing exception to log
			e.printStackTrace();
		} catch (IOException e) {
			// writing exception to log
			e.printStackTrace();

		}
	}
}
Ravi is hardcore Android programmer and Android programming has been his passion since he compiled his first hello-world program. Solving real problems of Android developers through tutorials has always been interesting part for him.
  • Pingback: Android Login and Registration with PHP, MySQL and SQLite()

  • what is the procedure to access the “remote database of website” please help….

  • KGPrakash

    Hi Ravi,

    How may I connect with username and password to my website’s login…?

  • jejeje

    your motherfucker, HIJO DE PUTA

  • vishal

    fack comment……………………

  • dinosaurclover

    This is not a tutrial, It’s an example.

    • jammin58

      While I appreciate “tutorial” posting I absolutely agree with dinosaurclover that this is more of an “example” than true tutorial.

  • Younes

    Add this if not working:

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()

    .permitAll().build();

    StrictMode.setThreadPolicy(policy);

  • goonerdroid

    Guys can i pass a String array in the Basic name value pair..if not then can you suggest some alternatives….help!!

  • flavio

    I downloaded your project and runs normal, but in my otros projects where the error on the line:

    HttpResponse response = httpClient.execute (HttpPost);

  • sdvipeen

    wats the output of this example.?

  • Abu Zahed Jony

    Thanks for the post. I am trying to post a string array.
    My code:
    for(String attachment : attachments){
    multipartEntity.addPart(“attachments[]”, new StringBody(attachment));
    }
    It is not working for me. server received full array as string( example “[“a”, “b”]” ). but I have to pas only string array (example- [“a”,”b”] ). Please help.

  • Sanny Singhs

    It’s very helpful. May know how to do the PUT and DELETE methods though

  • MM

    Hello Ravi. I’m trying to download the source code, but when I subscribe my e-mail I NEVER receive the confirmation in my e-mail, I already verify my spam box and tried another e-mail.

  • A way from Away

    can we do it for local server in our machine

  • Rafique Mohammed

    You are executing it on UIThread. Wont it throw exception and crash the APP?

  • Ndungu Njenga

    where do i download this library?

    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.json.JSONException;
    import org.json.JSONObject;

  • Rendy

    hello
    I found tutorial about httpclient and I have proble with httpost
    how to post with url parameter

    http://domain.com/api/cost?key=7867t6756&destination=89&weight=1000&origin=176
    this is what i want post to url >>
    key=7867t6756&destination=89&weight=1000&origin=176this my code:

    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpEntity httpEntity = null;
    HttpResponse httpResponse = null;

    if (method == POST) {
    HttpPost httpPost = new HttpPost(“http://domain.com/api/cost”);

    if (params != null) {

    httpPost.setHeader(“Accept”, “application/x-www-form-urlencoded”);
    httpPost.setHeader(“Content-type”, “application/x-www-form-urlencoded”);
    httpPost.setHeader(“Referer”, “key=7867t6756&destination=89&weight=1000&origin=176”);
    httpPost.setEntity(new UrlEncodedFormEntity(params));
    }
    httpResponse = httpClient.execute(httpPost);

    Thank you

  • Saad

    hello sir know i create an apps which is used to login for my site in device when i testing in bluestack
    it work means it send the user id and password to particualar URL when i install that apps in my real device it open when i click submit button it show unfortunatly your apps has been stopped i tried in any other device but it show same problem please help how to resolved this problem .

  • MajorTom8461

    I had this working for my localhost (wamp server), I could hit my database via a php page. Now I have hostgator and I cannot reach my php page with my URL. Does any one know how to fix this?

    – No errors its like its just not hitting the server.

    HttpPost httpPost = new HttpPost(“http://mydomain/login4.php”);

  • prince raizadha

    my lord thanks a lot
    i add some in this if it cause error of sticky in higher version than put this code before set layout

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

  • prasad

    Your tutorials are the most easy to understand tutorials in this planet. I learnt many concepts here. I want you to explain about what are web services, Different types of web services, methods used, creating a web service in java, how a web service receives request (HTTP, SOAP,REST etc. Not even one of them is understood by me), difference between a web service and servlet, how to create Database, save data in database via servelet/web service/ android application. Sorry as the list is too long. But I really liked the way you explain, and can easily understand. By the way I too live in Hyderabad

  • Hakan KANMAZ

    how can i post my data?
    { “OrgID”:”1″,
    “UserDepartment”:”1″,
    “WorkType”:”1977″,
    “WorkDefinition”:”EXAMPLE_EXAMPLE”,
    “Confirmed”:[
    {“Confirmed”:”qaAgo/+/j/XhECIhlAo2SQ==,}
    {“Confirmed”:”qaAgo/+/j/XhECIhlAo2SQ==”}],
    “FileName”:””,
    “FileMimeType”:””,
    “FileContent”:””
    }
    i write this codes but i couldn’t post
    public static void sendParameter(String organizationId, String departmentId, String workType, List comfirmedList, String fileName, String fileMimeType, String fileContent, String definition) {

    parameterList = new ArrayList();
    parameterList.add(new BasicNameValuePair(“OrgID”, organizationId));
    parameterList.add(new BasicNameValuePair(“UserDepartment”, departmentId));
    parameterList.add(new BasicNameValuePair(“WorkType”, workType));
    parameterList.add(new BasicNameValuePair(“Confirmed”, String.valueOf(comfirmedList)));
    parameterList.add(new BasicNameValuePair(“FileName”, fileName));
    parameterList.add(new BasicNameValuePair(“FileMimeType”, fileMimeType));
    parameterList.add(new BasicNameValuePair(“FileContent”, fileContent));
    parameterList.add(new BasicNameValuePair(“WorkDefinition”, definition));
    }

  • Nilesh

    Thanks for put this tutorial.
    but HttpClient is not working in my project for that what can i do?
    Is there any library which put in gradle.build ? or package or Build Tools which i not installed ?
    Thanks in advance.

  • hamad

    Can we add progress update with this code , please email me on

    hamad.kicsit@gmail.com

  • surya Mouly

    sir , i want to post data to server in json format using the same service handler class you have used in json parsing tutorial.. and i am getting trouble with this parameter List params can you plz help me out

  • Amitesh Banerjee

    Your tutorials are the best and easiest to understand.. however as httpclient is now depricated in latest android builds can you help me with this particular piece of code? I’ve tried a lot to convert this into httpurlconnection it simply doesnt work for me…

    HttpClient httpClient = new DefaultHttpClient();

    // Creating HTTP Post

    HttpPost httpPost = new HttpPost(link);

    //Name value pair created what you want to send to server

    List nameValuePair = new ArrayList(2);

    nameValuePair.add(new BasicNameValuePair(“Languages”,lang));

    nameValuePair.add(new BasicNameValuePair(“voice”,vc));

    nameValuePair.add(new BasicNameValuePair(“ex”,”execute”));

    nameValuePair.add(new BasicNameValuePair(“op”,text));

    nameValuePair.add(new BasicNameValuePair(“count”,count));

    nameValuePair.add(new BasicNameValuePair(“speed”,speed));

    //httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));

    httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair, “UTF-8”)); // UTF 8 added to send indic string to server

    HttpResponse httpResponse = httpClient.execute(httpPost);

    final int statusCode = httpResponse.getStatusLine().getStatusCode();

    Log.d(“Response Status Code”,String.valueOf(statusCode));

    } catch (UnsupportedEncodingException e) {

    // TODO Auto-generated catch block

    e.printStackTrace();

    } catch (ClientProtocolException e) {

    // TODO Auto-generated catch block

    e.printStackTrace();

    } catch (IOException e) {

    // TODO Auto-generated catch block

    e.printStackTrace();

    }

    and this is what i have coded for the httpurlconnection:

    URL url = new URL(link);

    urlConnection = (HttpURLConnection) url.openConnection();
    urlConnection.setReadTimeout(10000);
    urlConnection.setConnectTimeout(15000);
    urlConnection.setRequestMethod(“POST”);
    urlConnection.setDoInput(true);
    urlConnection.setDoOutput(true);
    urlConnection.setChunkedStreamingMode(0);
    urlConnection.setInstanceFollowRedirects(false);
    urlConnection.setRequestMethod(“POST”);

    Map param = new LinkedHashMap();
    param.put(“Languages”, lang);

    param.put(“voice”,vc);
    param.put(“ex”,”execute”);

    param.put(“op”,nt);
    param.put(“count”,count);
    param.put(“speed”,speed);

    StringBuilder postData = new StringBuilder();
    for (Map.Entry param1 : param .entrySet()) {
    if (postData.length() != 0) postData.append(‘&’);
    postData.append(URLEncoder.encode(param1.getKey(), “UTF-8”));
    postData.append(‘=’);
    postData.append(URLEncoder.encode(String.valueOf(param1.getValue()), “UTF-8”));
    }
    byte[] postDataBytes = postData.toString().getBytes(“UTF-8”);
    int postDataLength = postDataBytes.length;

    urlConnection.setRequestProperty( “charset”, “utf-8”);
    urlConnection.setRequestProperty( “Content-Length”, Integer.toString( postDataLength ));
    urlConnection.setUseCaches(false);
    urlConnection.getOutputStream().write(postDataBytes);
    Log.d(“getoutputstream”, postDataBytes.toString());

    InputStream in = new BufferedInputStream(urlConnection.getInputStream());
    // readStream(in);
    InputStreamReader isr = new InputStreamReader(in);
    BufferedReader br = new BufferedReader(isr);
    str = br.readLine();

    Log.d(“output of str”,str);
    } catch (MalformedURLException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    } finally {
    urlConnection.disconnect();
    }

    Please tell me what I am doing wrong?

  • Swati Gupta

    can you write android-making-http-requests using httpurlconnection ?

  • Vinita

    I am trying to add header :

    httpPost.setHeader(“deviceid”, “358978060711939”);
    httpPost.setHeader(“token”, “eyJ0eXOTI0ODkyM30.PAuNrDee1vi74”);

    but I am getting error:
    Authentication error: Unable to respond to any of these challenges.

    How can I add header?

  • Aman Rai

    Thnks for Tutorial.
    but i want to send Object in Name Value Pairs.. how i can send..
    ex.
    nameValuePair.add(new BasicNameValuePair(“email”, “user@gmail.com”));
    bt i want
    Inform infrm= new Inform;
    nameValuePair.add(new BasicNameValuePair(“inform”, inform));
    can i send Object Refernce like this. plz sir help me

  • K S UMA SANKAR

    I am trying for a HttpRequest

    I used the following program to import the class files

    import org.apache.http.HttpResponse;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.impl.client.DefaultHttpClient;

    I am getting cannot resolve HttpClient

  • Nasir Mushtaq

    i want to get the response and convert that into pdf file how can i do tha….my server actually creates pdf file of the data which i am sending throught post method using fpdf library .

  • ‫עידן בן שמעון‬‎

    Or you can just use this awesome library

    https://github.com/studioidan/HttpAgent

  • Geraldo K Fillipus

    Hi Ravi good tutorial

    I have an API developed in nodeJS, Express and Mongodb that i want to connect to my android, so can i use Apache to do the transaction between my API?

    Thankx

  • deepti

    next time please do mention which all jars to be added. I am facing so many errors and still google-ling to fix them 🙁

  • rahul patel

    hie sir i want to post data on json for that i need to append my url with id but its not working can u help me . plz show any exmple of appending url.

  • shiben

    Hi,

    I want to consume a RST API for instance.service-now.com

    Below is the code that i have

    package com.example.android.checkapi;

    import android.app.ProgressDialog;
    import android.content.Intent;
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.view.View;
    import android.widget.EditText;
    import android.widget.TextView;
    import android.widget.Toast;
    import com.loopj.android.http.AsyncHttpClient;
    import com.loopj.android.http.AsyncHttpResponseHandler;
    import com.loopj.android.http.RequestParams;

    import org.json.JSONException;
    import org.json.JSONObject;

    import cz.msebera.android.httpclient.Header;

    public class MainActivity extends AppCompatActivity {

    // Progress Dialog Object
    ProgressDialog prgDialog;
    // Error Msg TextView Object
    TextView errorMsg;
    // Email Edit View Object
    EditText emailET;
    // Passwprd Edit View Object
    EditText pwdET;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    // Find Error Msg Text View control by ID
    errorMsg = (TextView)findViewById(R.id.login_error);
    // Find Email Edit View control by ID
    emailET = (EditText)findViewById(R.id.loginEmail);
    // Find Password Edit View control by ID
    pwdET = (EditText)findViewById(R.id.loginPassword);
    // Instantiate Progress Dialog object
    prgDialog = new ProgressDialog(this);
    // Set Progress Dialog Text
    prgDialog.setMessage(“Please wait…”);
    // Set Cancelable as False
    prgDialog.setCancelable(false);
    }

    /**
    * Method gets triggered when Login button is clicked
    *
    * @param view
    */

    public void loginMain(View view){

    // Get Email Edit View Value
    String email = emailET.getText().toString();
    // Get Password Edit View Value
    String password = pwdET.getText().toString();
    // Instantiate Http Request Param Object
    RequestParams params = new RequestParams();
    // When Email Edit View and Password Edit View have values other than Null
    /**if(Utility.isNotNull(email) && Utility.isNotNull(password)){
    // When Email entered is Valid
    if(Utility.validate(email)){*/
    // Put Http parameter username with value of Email Edit View control
    params.put(“username”, email);
    // Put Http parameter password with value of Password Edit Value control
    params.put(“password”, password);
    // Invoke RESTful Web Service with Http parameters
    invokeWS(params);
    //}
    }

    /**
    * Method that performs RESTful webservice invocations
    *
    * @param params
    */

    public void invokeWS(RequestParams params){
    // Show Progress Dialog
    prgDialog.show();
    // Make RESTful webservice call using AsyncHttpClient object
    AsyncHttpClient client = new AsyncHttpClient();
    client.get(”

    https://instance.service-now.com/api/now/table/problem?sysparm_limit=1

    “,params ,new AsyncHttpResponseHandler() {

    public void onSuccess(int status_code, Header[] headers, byte[] responseBody) {

    // Hide Progress Dialog
    prgDialog.hide();
    try {
    // JSON Object
    JSONObject obj = new JSONObject(String.valueOf(responseBody));
    // When the JSON response has status boolean value assigned with true
    if (obj.get(“status_code”).equals(“200”)){
    Toast.makeText(getApplicationContext(), “You are successfully logged in!”, Toast.LENGTH_LONG).show();
    // Navigate to Home screen
    navigatetoHomeActivity();
    }
    // Else display error message
    else{
    errorMsg.setText(obj.getString(“error_msg”));
    Toast.makeText(getApplicationContext(), obj.getString(“error_msg”), Toast.LENGTH_LONG).show();
    }
    } catch (JSONException e) {
    // TODO Auto-generated catch block
    Toast.makeText(getApplicationContext(), “Error Occured [Server’s JSON response might be invalid]!”, Toast.LENGTH_LONG).show();
    e.printStackTrace();

    }
    }
    // When the response returned by REST has Http response code other than ‘200’
    @Override
    public void onFailure(int status_code, Header[] headers, byte[] responseBody, Throwable error) {
    // Hide Progress Dialog
    prgDialog.hide();
    // When Http response code is ‘404’
    if(status_code == 404){
    Toast.makeText(getApplicationContext(), “Requested resource not found”, Toast.LENGTH_LONG).show();
    }
    // When Http response code is ‘500’
    else if(status_code == 500){
    Toast.makeText(getApplicationContext(), “Something went wrong at server end”, Toast.LENGTH_LONG).show();
    }
    // When Http response code other than 404, 500
    else{
    Toast.makeText(getApplicationContext(), “Unexpected Error occcured! [Most common Error: Device might not be connected to Internet or remote server is not up and running]”, Toast.LENGTH_LONG).show();
    }
    }
    });

    }
    /**
    * Method which navigates from Login Activity to Home Activity
    */
    public void navigatetoHomeActivity(){
    Intent homeIntent = new Intent(getApplicationContext(),HomeActivity.class);
    homeIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(homeIntent);
    }
    }

    I get the error : Unexpected Error occcured! [Most common Error: Device might not be
    connected to Internet or remote server is not up and running]”

    I have used the below in manifest file

    What could i be doing wrong ?

    Please help