Wednesday, 29 May 2013

Android HTTP Client

Most network-connected Android apps use HTTP to send and receive data.

Android includes two HTTP clients:HttpURLConnection and Apache HttpClient.

For android HttpURLConnection recommended.

Http URL Connection simplifies connections to HTTP servers.
  •  The base class for HTTP network access in the java.net package is the HttpURLConnectionclass.
  •  The preferred way of accessing the Internet according to Google is the HttpURLConnection class,  as Google is focusing their efforts on improving this implementation.
  • HttpURLConnection which is also available in standard Java, is a general-purpose, lightweight HTTP client suitable for most applications.
Getting a connection from a URL
URL url = new URL("http://www.google.com");
HttpURLConnection urlConnection =(HttpURLConnection)url.openConnection();

Reading data
BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
while ((line = in.readLine()) != null) {
doSomethingWith(line);
}