Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save adilmughal/3117827 to your computer and use it in GitHub Desktop.
Save adilmughal/3117827 to your computer and use it in GitHub Desktop.
This code snippet demostrates the usage of AsyncTask to perform HttpPut request asynchrously and avoiding NetworkOnMainThread exception in android
package samples.android;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import android.os.AsyncTask;
import android.util.Log;
public class AsyncHttpRequestManager extends AsyncTask<String, Boolean, String> {
private final String serviceUrl = "http://MACHINE_IP_HERE/DemoCalculatorRestfulServices/resources/utility/";
@Override
protected String doInBackground(String... params) {
try {
DefaultHttpClient client = new DefaultHttpClient();
HttpPut putRequest = new HttpPut(serviceUrl);
putRequest.setHeader("Content-type", "text/plain");
putRequest.setHeader("Accept", "text/plain");
putRequest.setEntity(new StringEntity(params[0]));
HttpResponse response = client.execute(putRequest);
InputStream content = response.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String result = "";
String s = "";
while ((s = buffer.readLine()) != null) {
result += s;
}
return result;
}
catch (UnsupportedEncodingException e) {
Log.e("AsyncOperationFailed", e.getMessage());
e.printStackTrace();
} catch (ClientProtocolException e) {
Log.e("AsyncOperationFailed", e.getMessage());
e.printStackTrace();
} catch (IOException e) {
Log.e("AsyncOperationFailed", e.getMessage());
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String result) {
Log.d("MESSAGE", result);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment