Android, Java: Http Post Request

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
}
}

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 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.

Android Java Http Request Post

The first problem may be that you didn't add the INTERNET permission in your AndroidManifest.xml. To resolve this just add this line <uses-permission android:name="android.permission.INTERNET" /> in your manifest.

The other problem is that you're trying to execute a post request on main thread. It causes NetworkOnMainThreadException. You should use AsyncTask or Handler to execute network requests, like this:

public class MainActivity extends ActionBarActivity {

private static final String TAG = "victorMessage";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i(TAG, "onCreate");
new HttpPostTask().execute();
}

private class HttpPostTask extends AsyncTask<Void, Void, String> {

@Override
protected String doInBackground(Void... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://93.117.158.187/");

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);

Log.i(TAG, response.toString());
return response.toString();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}

return null;
}

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

//do something with you response, connected with UI thread.
}
}
}

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.

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!

HTTP POST Request as a different Java Class - Android Studio

your con use feature interface

   public class HTTPReq {
public void postRequest(final HashMap<String, String> params, final Context context, final ResponseCallBack callBack) {
RequestQueue requestQueue = Volley.newRequestQueue(context);
String url = "https://reqres.in/api/login";
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {

@Override
public void onResponse(String response) {
callBack.onResponse(response);
Toast.makeText(context, response, Toast.LENGTH_LONG).show();

}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
callBack.onError(error);
Toast.makeText(context, "Response Failed", Toast.LENGTH_LONG).show();
}
}) {
@Override
protected Map<String, String> getParams() {
return params;
}

@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/x-www-form-urlencoded");
return params;
}
};

requestQueue.add(stringRequest);

}
}

calss interface :

import com.android.volley.VolleyError;

public interface ResponseCallBack<T> {
public void onResponse(T response);

public void onError(VolleyError error_response);


}

MainActivity:

public class MainActivity extends AppCompatActivity implements ResponseCallBack {

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

HTTPReq httpReq = new HTTPReq();
HashMap<String, String> credentials = new HashMap<String, String>();
credentials.put("email", "eve.holt@reqres.in");
credentials.put("password", "cityslicka");

httpReq.postRequest(credentials, this, this);

}

@Override
public void onResponse(Object response) {
Log.e("TAG", "onResponse: " + response);
}

@Override
public void onError(VolleyError error_response) {

Log.e("TAG", "onError: " + error_response);
}

Can't send a correct POST request in Java (Android Studio)

I have just tried to create an User and it worked. You can refresh the link u have shared to check the created User.

This is what I have tried

String endPoint= "https://safe-citadel-91138.herokuapp.com/questions";
try {

DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost(endPoint);
post.addHeader("Content-Type", "application/json");
JSONObject obj = new JSONObject();

obj.put("firstName", "TESTF");
obj.put("lastName", "TESTL");
obj.put("email", "support@mlab.com");

StringEntity entity = new StringEntity(obj.toString());
post.setEntity(entity);
HttpResponse response = httpClient.execute(post);
}catch (Exception e){

}

UPDATE

BTW I have used json jar from this link

Example of POST request in Android studio

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



Related Topics



Leave a reply



Submit