WebResponce in Android

Posted: July 31, 2012 in Android
Tags: , ,

Hello Droids..!

Here i am demonstrating a class file which will be very helpful in getting web-response. I read so many comments on Web-Response that giving error in fetching.

So here is the .java file into which you just have to pass the URL! and in response you will get String value! That’s it!  Easy and handy!

Here is the Code,


import java.io.ByteArrayOutputStream;
import java.io.IOException;
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;

public class WebResponse {

	public String getWebResponse(String URL)
	{
	  HttpClient httpclient = new DefaultHttpClient();
      HttpResponse response;
     String responseString = "";
      try {

//           String temp = URL;
//              temp = temp.replaceAll(" ","%20");

          response = httpclient.execute(new HttpGet(URL));
          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) {
          //TODO Handle problems..

      } catch (IOException e) {
          //TODO Handle problems..
      e.printStackTrace();
      }
      return responseString;
	}

}

How to use:

//first create an object of this class file
WebResponse wr = new WebResponse();
String resp = wr.getWebResponse(your url); //add your url

Download here:: WebResponse.java

Comments will be appreciated. 🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s