Friday, December 28, 2012

Android: Using HttpClient to execute GET requests

The following code shows a simple utility method that will execute a HTTP GET Request and return the response in a simple Value Object.

Class that is used to hold the HTTP Response from the server.

public class HttpResponseContainerVO {

//Add any additional headers you require.
private int responseCode;

private long contentLength;

private long requestTime;

private int cacheControl;

private String contentType;

private String response;

 // Getters and Setters for all the fields.
}

Method to query and retrieve the Contents of a URL

public static HttpResponseContainerVO getResponse(String url,
Map params)
throws IOException {
 
HttpResponseContainerVO responseVo = new HttpResponseContainerVO();

DefaultHttpClient client = new DefaultHttpClient();

HttpGet get = new HttpGet(url);
if (params != null && !params.isEmpty()) {
// Add the params to GET object in the URL
// ? & ...
}

 
//Setting headers
get.addHeader(new BasicHeader("User-Agent", "--VALUE---"));

 
HttpResponse response = client.execute(get);
HttpEntity entity = response.getEntity();

responseVo.setResponseCode(response.getStatusLine().getStatusCode());
Header[] headers = response.getAllHeaders();
for (Header hdr : headers) {
  
//Read all the headers and set value to responseVO

}

InputStream inputStream = entity.getContent();
ByteArrayOutputStream content = new ByteArrayOutputStream();

// Read response into a buffered stream
int readBytes = 0;
byte[] sBuffer = new byte[512];
while ((readBytes = inputStream.read(sBuffer)) != -1) {
content.write(sBuffer, 0, readBytes);
}
responseVo.setResponse(new String(content.toByteArray()));

return responseVo;
}

No comments:

Post a Comment