Back to project page Recipe-Puppy-Android.
The source code is released under:
Apache License
If you think the Android project Recipe-Puppy-Android listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.
package com.jerin.utilities; //from www.j a v a 2s . c om import java.io.ByteArrayOutputStream; import java.io.IOException; import java.lang.ref.WeakReference; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.StatusLine; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import android.os.AsyncTask; import android.util.Log; /** * Performs HTTP Request in the background. * * @author jerin * */ public class RequestTask extends AsyncTask<String, String, String> { private static final String _TAG = RequestTask.class.getSimpleName(); private WeakReference<IRequestResponseListener> listenerRefernce; @Override protected String doInBackground(String... uri) { HttpClient httpclient = new DefaultHttpClient(); HttpResponse response; String responseString = null; try { response = httpclient.execute(new HttpGet(uri[0])); StatusLine statusLine = response.getStatusLine(); if (statusLine.getStatusCode() == HttpStatus.SC_OK) { ByteArrayOutputStream out = new ByteArrayOutputStream(); response.getEntity().writeTo(out); out.close(); responseString = out.toString(); } else { // Closes the connection. response.getEntity().getContent().close(); throw new IOException(statusLine.getReasonPhrase()); } } catch (ClientProtocolException e) { // Handle problems.. Log.e(_TAG, e.getMessage()); } catch (IOException e) { // Handle problems.. Log.e(_TAG, e.getMessage()); } return responseString; } @Override protected void onPostExecute(String response) { super.onPostExecute(response); // Intimate listener of the response if (null != listenerRefernce) { IRequestResponseListener requestResponseListener = listenerRefernce .get(); if (null != requestResponseListener) { requestResponseListener.onRequestComplete(response); } } } public void setListener(IRequestResponseListener listener) { this.listenerRefernce = new WeakReference<RequestTask.IRequestResponseListener>( listener); } /** * Fragments or Activities which initiate a RequestTask must implement this * interface to get a callback once response is recieved. * * @author jerin * */ public interface IRequestResponseListener { void onRequestComplete(String response); } }