Android Project Using Httpclient --> Http.Client (Apache), Post/Get Method

Android project using httpclient -- http.client (apache), post/get method

The easiest way to answer my question is to show you the class that I made :

public class HTTPHelp{

DefaultHttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
private boolean abort;
private String ret;

HttpResponse response = null;
HttpPost httpPost = null;

public HTTPHelp(){

}

public void clearCookies() {

httpClient.getCookieStore().clear();

}

public void abort() {

try {
if(httpClient!=null){
System.out.println("Abort.");
httpPost.abort();
abort = true;
}
} catch (Exception e) {
System.out.println("HTTPHelp : Abort Exception : "+e);
}
}

public String postPage(String url, String data, boolean returnAddr) {

ret = null;

httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109);

httpPost = new HttpPost(url);
response = null;

StringEntity tmp = null;

httpPost.setHeader("User-Agent", "Mozilla/5.0 (X11; U; Linux " +
"i686; en-US; rv:1.8.1.6) Gecko/20061201 Firefox/2.0.0.6 (Ubuntu-feisty)");
httpPost.setHeader("Accept", "text/html,application/xml," +
"application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");

try {
tmp = new StringEntity(data,"UTF-8");
} catch (UnsupportedEncodingException e) {
System.out.println("HTTPHelp : UnsupportedEncodingException : "+e);
}

httpPost.setEntity(tmp);

try {
response = httpClient.execute(httpPost,localContext);
} catch (ClientProtocolException e) {
System.out.println("HTTPHelp : ClientProtocolException : "+e);
} catch (IOException e) {
System.out.println("HTTPHelp : IOException : "+e);
}
ret = response.getStatusLine().toString();

return ret;
}
}

I used this tutorial to do my post method and thoses examples

Make an HTTP request with android

UPDATE

This is a very old answer. I definitely won't recommend Apache's client anymore. Instead use either:

  • Retrofit
  • OkHttp
  • Volley
  • HttpUrlConnection

Original Answer

First of all, request a permission to access network, add following to your manifest:

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

Then the easiest way is to use Apache http client bundled with Android:

    HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(new HttpGet(URL));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
String responseString = out.toString();
out.close();
//..more logic
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}

If you want it to run on separate thread I'd recommend extending AsyncTask:

class RequestTask extends AsyncTask<String, String, String>{

@Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
responseString = out.toString();
out.close();
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
//TODO Handle problems..
} catch (IOException e) {
//TODO Handle problems..
}
return responseString;
}

@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//Do anything with response..
}
}

You then can make a request by:

   new RequestTask().execute("http://stackoverflow.com");

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

Android HttpClient, DefaultHttpClient, HttpPost

I think in your code the basic problem is caused by the way you are using StringEntity to POST parameters to your url. Check to see if the following code helps in posting your data to the server using StringEntity.

    // Build the JSON object to pass parameters
JSONObject jsonObj = new JSONObject();
jsonObj.put("username", username);
jsonObj.put("data", dataValue);

// Create the POST object and add the parameters
HttpPost httpPost = new HttpPost(url);
StringEntity entity = new StringEntity(jsonObj.toString(), HTTP.UTF_8);
entity.setContentType("application/json");
httpPost.setEntity(entity);

HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(httpPost);

Hope this helps in solving your problem. Thanks.

Using HttpClient and HttpPost in Android with post parameters

have you tried doing it without the JSON object and just passed two basicnamevaluepairs?
also, it might have something to do with your serversettings

Update:
this is a piece of code I use:

InputStream is = null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("lastupdate", lastupdate));

try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(connection);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.d("HTTP", "HTTP: OK");
} catch (Exception e) {
Log.e("HTTP", "Error in http connection " + e.toString());
}

Android HTTP Request with HttpClient and AsyncHttpClient

you crash it is because

 Log.i("Data", result);

correct with:

Log.i("Data", ""+result);

Than just check why is null the result. some OS version can't read the 401 response message, needed a hack to do it

HTTP Post requests using HttpClient take 2 seconds, why?

Allright, I solved this myself with some more investigation. All I had to do was to add a parameter that sets the HTTP Version to 1.1, as follows:

HttpParams params = new BasicHttpParams();
params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpClient httpclient = new DefaultHttpClient(params);

I found this thanks to the very nice HttpHelper Class from and-bookworm and some trial-and-error.

If I remember correctly, HTTP 1.0 opens a new TCP connection for every request. Does that explain the large delay?

A HTTP POST request now takes between 50 and 150 ms over WLAN and something between 300 and 500 ms over 3G.

I need an alternative option to HttpClient in Android to send data to PHP as it is no longer supported

The HttpClient was deprecated and now removed:

org.apache.http.client.HttpClient:

This interface was deprecated in API level 22.
Please use openConnection() instead. Please visit this webpage for further details.

means that you should switch to java.net.URL.openConnection().

See also the new HttpURLConnection documentation.

Here's how you could do it:

URL url = new URL("http://some-server");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");

// read the response
System.out.println("Response Code: " + conn.getResponseCode());
InputStream in = new BufferedInputStream(conn.getInputStream());
String response = org.apache.commons.io.IOUtils.toString(in, "UTF-8");
System.out.println(response);

IOUtils documentation: Apache Commons IO

IOUtils Maven dependency: http://search.maven.org/#artifactdetails|org.apache.commons|commons-io|1.3.2|jar



Related Topics



Leave a reply



Submit