Created
July 15, 2012 17:34
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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