Search with Restful service
package app.test;
import java.net.URI;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.TextView;
class RestTask extends AsyncTask<HttpUriRequest, Void, String> {
public static final String HTTP_RESPONSE = "httpResponse";
private Context mContext;
private HttpClient mClient;
private String mAction;
public RestTask(Context context, String action) {
mContext = context;
mAction = action;
mClient = new DefaultHttpClient();
}
public RestTask(Context context, String action, HttpClient client) {
mContext = context;
mAction = action;
mClient = client;
}
@Override
protected String doInBackground(HttpUriRequest... params) {
try {
HttpUriRequest request = params[0];
HttpResponse serverResponse = mClient.execute(request);
BasicResponseHandler handler = new BasicResponseHandler();
String response = handler.handleResponse(serverResponse);
return response;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
@Override
protected void onPostExecute(String result) {
Intent intent = new Intent(mAction);
intent.putExtra(HTTP_RESPONSE, result);
// Broadcast the completion
mContext.sendBroadcast(intent);
}
}
public class Test extends Activity {
private static final String SEARCH_ACTION = "com.examples.rest.SEARCH";
private static final String SEARCH_URI = "http://search.yahooapis.com/WebSearchService/V1/webSearch?appid=%s&query=%s";
private TextView result;
private ProgressDialog progress;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("Activity");
result = new TextView(this);
setContentView(result);
try {
String url = String.format(SEARCH_URI, "YahooDemo", "Android");
HttpGet searchRequest = new HttpGet(new URI(url));
RestTask task = new RestTask(this, SEARCH_ACTION);
task.execute(searchRequest);
progress = ProgressDialog.show(this, "Searching","Waiting For Results...", true);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onResume() {
super.onResume();
registerReceiver(receiver, new IntentFilter(SEARCH_ACTION));
}
@Override
public void onPause() {
super.onPause();
unregisterReceiver(receiver);
}
private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (progress != null) {
progress.dismiss();
}
String response = intent.getStringExtra(RestTask.HTTP_RESPONSE);
result.setText(response);
}
};
}
Related examples in the same category