Skip to content

Instantly share code, notes, and snippets.

@paschalis-mpeis
Last active December 19, 2015 10:19
Show Gist options
  • Save paschalis-mpeis/5939967 to your computer and use it in GitHub Desktop.
Save paschalis-mpeis/5939967 to your computer and use it in GitHub Desktop.
Android HTTP Post request, in an Asynchronous background process
/**
* Paschalis Mpeis
* paschalis.mp
*
* Usage: AsyncPostRequest r = new AsyncPostRequest(url, parameters); r.execute();
*/
/**
* AsyncPostRequest class
*/
public static class AsyncPostRequest extends AsyncTask<Object, Integer, String> {
final ArrayList<NameValuePair> mNameValuePairs;
final String url;
public AsyncPostRequest(String url, ArrayList<NameValuePair> nameValuePairs) {
this.mNameValuePairs = nameValuePairs; // The parameters to the post request
this.url = url;
}
/**
* @param link of the PHP Script
* @param values to build the PHP Post (eg. username=abc)
* @return JSON Object with the result
*/
public static String httpPostRequest(String link,
ArrayList<NameValuePair> values) {
String result = null;
InputStream inputStream = null;
try {
// HttpClient will execute the Post
HttpClient httpclient = new DefaultHttpClient();
// Make new HTTP Post @link
HttpPost httppost = new HttpPost(link);
// Put variables on the HTTP Post
httppost.setEntity(new UrlEncodedFormEntity(values));
// Execute & get the response
HttpResponse response = httpclient.execute(httppost);
// Save response in InputStream
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// Convert response
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream, "iso-8859-1"), 8);
StringBuilder stringBuilder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line + "\n");
}
// Close Stream
inputStream.close();
result = stringBuilder.toString();
} catch (Exception e1) {
Log.e(TAG, "Error in http.post " + e1.toString());
return null;
}
// Return result
return result;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
//Show progress bar in actionbar
// activity.setProgressBarIndeterminateVisibility(true);
//Disable menu buttons
}
@Override
protected String doInBackground(Object... objects) {
return httpPostRequest(url, mNameValuePairs);
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//to Hide progress bar in actionbar
// activity.setProgressBarIndeterminateVisibility(false);
// Run functions when finished
Log.e(TAG, "Result got: " + result);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment