Wednesday, May 27, 2009

HTTP GET and POST Thread Service on Android

HttpService.java
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;

public class HttpService implements Runnable {

private static final String TAG = "HttpService";
public static final int GET = 0;
public static final int POST = 1;
public static final String HTTP_RESPONSE = "HTTP_RESPONSE";

private Activity activity;
private Intent intent;
private int requestCode;
private String url;
private int getOrPost = 0;
private List<NameValuePair> nameValuePairs;
private boolean handleByMe;

/*
* for example:
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("aaa", "bbb"));
nameValuePairs.add(new BasicNameValuePair("ccc", "ddd"));
*/
public HttpService(Activity activity, Intent intent, int requestCode, String url, int getOrPost, List<NameValuePair> nameValuePairs, boolean handleByMe){
this.activity = activity;
this.intent = intent;
this.requestCode = requestCode;
this.url = url;
this.getOrPost = getOrPost;
this.nameValuePairs = nameValuePairs;
this.handleByMe = handleByMe;
}

public void start(){
Thread thread = new Thread(this);
try{
thread.start();
}catch(IllegalThreadStateException itse){
Log.e(TAG, "The Thread has been started before.", itse);
}
}

public void run() {
doRequest();
}

public void doRequest(){
HttpClient httpclient = new DefaultHttpClient();
HttpRequestBase httpRequest = null;
HttpResponse httpResponse = null;
InputStream inputStream = null;
String response = "";
StringBuffer buffer = new StringBuffer();

if(POST == getOrPost){
httpRequest = new HttpPost(url);
try {
((HttpPost)httpRequest).setEntity(new UrlEncodedFormEntity(nameValuePairs));
} catch (UnsupportedEncodingException usee) {
Log.e(TAG, "Could not encode the nameVaulePairs.", usee);
}
}else{
httpRequest = new HttpGet(url);
}
if(httpRequest != null){
try{
httpResponse = httpclient.execute(httpRequest);
inputStream = httpResponse.getEntity().getContent();
int contentLength = (int) httpResponse.getEntity().getContentLength();
if (contentLength < 0){
Log.e(TAG, "The HTTP response is too long.");
}
byte[] data = new byte[256];
int len = 0;
while (-1 != (len = inputStream.read(data)) )
{
buffer.append(new String(data, 0, len));
}
inputStream.close();
}catch (ClientProtocolException cpe) {
Log.e(TAG, "Http protocol error occured.", cpe);
}catch (IllegalStateException ise) {
Log.e(TAG, "Could not get a HTTP response from the server.", ise);
}catch (IOException ioe) {
Log.e(TAG, "Could not establish a HTTP connection to the server or could not get a response properly from the server.", ioe);
}
}
response = buffer.toString();
intent.putExtra(HTTP_RESPONSE, response);

if(handleByMe){
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
activity.startActivity(intent);
}else{
activity.startActivityForResult(intent, requestCode);
}
}

}



How to use it?
Intent intent = new Intent(this, SkeletonActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
HttpService httpService = new HttpService(this, intent, 0, "http://www.google.com", 0, null, true);
httpService.start();


protected void onNewIntent(Intent intent) {
String message = intent.getStringExtra(HttpService.HTTP_RESPONSE);
editor.setText(message);
}

3 comments:

  1. Am I missing how this gets called in the manifest as a service?

    ReplyDelete
  2. actually it isn't a android service, it is a business service. But anyway you can modify it and make it as a android service, that's easy.

    ReplyDelete
  3. I absolutely appreciate your way of presenting this column with a excellent suggestion.I want some more about this article. So you can add some interesting information and it will easily to reach the branding.

    ReplyDelete