Android Http Clients
In Android, we can choose 3(2) choices.
- HttpURLConnection
- Apache HttpClient
- AndroidHttpClient
In old version, HttpClient is not bundled I thought.
But, it is not latest version.
Permission
To use HttpClient(internet connection), we need to enable a permission.
<uses-permission android:name="android.permission.INTERNET" />
HttpURLConnection
It seems to be steadily. Easy to use for general-purpose.
Compare to Apache HttpClient, customize is difficult, but stable.
Sample
InputStream is = null;
try
{
URL url new URL("http://www.google.com");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.connect();
int response = conn.getResponseCode();
if ( response == 200 )
{
is = conn.getInputStream();
}
}
finally
{
if ( is != null )
{
is.close();
}
}
Apache HttpClient
Few bugs but, can customize. Also can use variety purpose.
DefaultHttpClient is common use in Java.
HttpClient httpClient = new DefaultHttpClient();
try
{
HttpResponse httpResponse;
HttpGet request = new HttpGet("http://www.google.com");
HttpResponse res = httpClient.execute(hget);
// httpResponse.getEntity()
}
catch (IOException oops)
{
oops.printStackTrace();
// Fail
}
finally
{
httpClient.getConnectionManager().shutdown();
}
AndroidHttpClient
AndroidHttpClient is extend of DefaultHttpClient.
It is set appropriate paramesters for Android.
Actually, it is the best choice for easy use.
Sample
AndroidHttpClient httpClient = AndroidHttpClient.newInstance("Android");
try {
HttpGet hget= new HttpGet("http://www.google.com");
HttpResponse res = httpClient.execute(hget);
if (res.getStatusLine().getStatusCode() == 200)
{
//IOUtils.copy(res.getEntity().getContent(), new FileOutputStream(new File(path)));
//res.getEntity().getContent(); This is content
}
}
catch (IOException oops)
{
oops.printStackTrace();
// Fail
}
finally
{
httpClient.getConnectionManager().shutdown();
}
References
Google Developer”
Android Developer’s Blog
TechBooster
