How to Do a Http Post in Android

Sending POST data in Android

Note (Oct 2020): AsyncTask used in the following answer has been deprecated in Android API level 30. Please refer to Official documentation or this blog post for a more updated example

Updated (June 2017) Answer which works on Android 6.0+. Thanks to @Rohit Suthar, @Tamis Bolvari and @sudhiskr for the comments.

    public class CallAPI extends AsyncTask<String, String, String> {

public CallAPI(){
//set context variables if required
}

@Override
protected void onPreExecute() {
super.onPreExecute();
}

@Override
protected String doInBackground(String... params) {
String urlString = params[0]; // URL to call
String data = params[1]; //data to post
OutputStream out = null;

try {
URL url = new URL(urlString);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
out = new BufferedOutputStream(urlConnection.getOutputStream());

BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
writer.write(data);
writer.flush();
writer.close();
out.close();

urlConnection.connect();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}

References:

  • https://developer.android.com/reference/java/net/HttpURLConnection.html
  • How to add parameters to HttpURLConnection using POST using NameValuePair

Original Answer (May 2010)

Note: This solution is outdated. It only works on Android devices up to 5.1. Android 6.0 and above do not include the Apache http client used in this answer.

Http Client from Apache Commons is the way to go. It is already included in android. Here's a simple example of how to do HTTP Post using it.

public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");

try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "Hi"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);

} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}

Sending HTTP Post Request with Android

You can use Http Client from Apache Commons. For example:

private class PostTask extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... data) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://<ip address>:3000");

try {
//add data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("data", data[0]));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//execute http post
HttpResponse response = httpclient.execute(httppost);

} catch (ClientProtocolException e) {

} catch (IOException e) {

}
}
}

UPDATE

You can use Volley Android Networking Library to post your data. Official document is here.

I personally use Android Asynchronous Http Client for few REST Client projects.

Other tool that good to explore is Retrofit.

How to send http post request from Android?

I am using this code and working as well. Try this code.

public static String httpPostRequest(Context context, String url, String email) {
String response = "";
BufferedReader reader = null;
HttpURLConnection conn = null;
try {
LogUtils.d("RequestManager", url + " ");
LogUtils.e("data::", " " + data);
URL urlObj = new URL(url);

conn = (HttpURLConnection) urlObj.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());

data += "&" + URLEncoder.encode("Email", "UTF-8") + "="
+ URLEncoder.encode(email, "UTF-8");

wr.write(data);
wr.flush();

LogUtils.d("post response code", conn.getResponseCode() + " ");

int responseCode = conn.getResponseCode();

reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;

while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}

response = sb.toString();
} catch (Exception e) {
e.printStackTrace();
LogUtils.d("Error", "error");
} finally {
try {
reader.close();
if (conn != null) {
conn.disconnect();
}
} catch (Exception ex) {
}
}
LogUtils.d("RESPONSE POST", response);
return response;
}

Sending POST request in android studio

to answer your question #3 would suggest using a library like OkHTTP to make that post request. That will make your code way simpler and easier to debug.

Make sure you have the following permissions on your Manifest:

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

Add the library to your gradle file:

compile 'com.squareup.okhttp3:okhttp:3.10.0'

Then, change your onCreate method to the following:

private final OkHttpClient client = new OkHttpClient();

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

ActionBar actionBar = this.getSupportActionBar();
actionBar.setTitle("Test");
actionBar.setDisplayHomeAsUpEnabled(true);

makePost();
}

private void makePost(){
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("email", "your-email@email.com")
.addFormDataPart("name", "your-name")
.build();

request = new Request.Builder()
.url("http://myip/task_manager/v1/register")
.post(requestBody)
.build();

try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

Headers responseHeaders = response.headers();
for (int i = 0; i < responseHeaders.size(); i++) {
System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
}

System.out.println(response.body().string());
}
}

And this should make a post request to your endpoint.

If you wanna log it, you can just add a logging interceptor to it.

Hope this helps you out!

Example of POST request in Android studio

Use Volley as defined here. It's far more easier.

How to do a HTTP Post in Android?

Use this class:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class HttpLogin extends Activity {
/** Called when the activity is first created. */
private Button login;
private EditText username, password;

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

login = (Button) findViewById(R.id.login);
username = (EditText) findViewById(R.id.username);
password = (EditText) findViewById(R.id.password);

login.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {

String mUsername = username.getText().toString();
String mPassword = password.getText().toString();

tryLogin(mUsername, mPassword);
}
});
}

protected void tryLogin(String mUsername, String mPassword)
{
HttpURLConnection connection;
OutputStreamWriter request = null;

URL url = null;
String response = null;
String parameters = "username="+mUsername+"&password="+mPassword;

try
{
url = new URL("your login URL");
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestMethod("POST");

request = new OutputStreamWriter(connection.getOutputStream());
request.write(parameters);
request.flush();
request.close();
String line = "";
InputStreamReader isr = new InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
// Response from server after login process will be stored in response variable.
response = sb.toString();
// You can perform UI operations here
Toast.makeText(this,"Message from Server: \n"+ response, 0).show();
isr.close();
reader.close();

}
catch(IOException e)
{
// Error
}
}
}

main.xml will be like this:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<EditText android:hint="Username" android:id="@+id/username" android:layout_width="fill_parent" android:layout_height="wrap_content"></EditText>
<EditText android:hint="Password" android:id="@+id/password" android:layout_width="fill_parent" android:layout_height="wrap_content" android:inputType="textPassword"></EditText>
<Button android:text="Sign In" android:id="@+id/login" android:layout_width="fill_parent" android:layout_height="wrap_content"></Button>
</LinearLayout>

Android GET and POST Request

You can use the HttpURLConnection class (in java.net) to send a POST or GET HTTP request. It is the same as any other application that might want to send an HTTP request. The code to send an Http Request would look like this:

import java.net.*;
import java.io.*;
public class SendPostRequest {
public static void main(String[] args) throws MalformedURLException, IOException {
URL reqURL = new URL("http://www.stackoverflow.com/"); //the URL we will send the request to
HttpURLConnection request = (HttpURLConnection) (reqUrl.openConnection());
String post = "this will be the post data that you will send"
request.setDoOutput(true);
request.addRequestProperty("Content-Length", Integer.toString(post.length)); //add the content length of the post data
request.addRequestProperty("Content-Type", "application/x-www-form-urlencoded"); //add the content type of the request, most post data is of this type
request.setMethod("POST");
request.connect();
OutputStreamWriter writer = new OutputStreamWriter(request.getOutputStream()); //we will write our request data here
writer.write(post);
writer.flush();
}
}

A GET request will look a little bit different, but much of the code is the same. You don't have to worry about doing output with streams or specifying the content-length or content-type:

import java.net.*;
import java.io.*;

public class SendPostRequest {
public static void main(String[] args) throws MalformedURLException, IOException {
URL reqURL = new URL("http://www.stackoverflow.com/"); //the URL we will send the request to
HttpURLConnection request = (HttpURLConnection) (reqUrl.openConnection());
request.setMethod("GET");
request.connect();

}
}

Android, Java: HTTP POST Request

Here's an example previously found at androidsnippets.com (the site is currently not maintained anymore).

// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");

try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);

} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}

So, you can add your parameters as BasicNameValuePair.

An alternative is to use (Http)URLConnection. See also Using java.net.URLConnection to fire and handle HTTP requests. This is actually the preferred method in newer Android versions (Gingerbread+). See also this blog, this developer doc and Android's HttpURLConnection javadoc.



Related Topics



Leave a reply



Submit