Android Projects

Android Development Books

Tuesday

UrlConnection in Android

If you need to connect to internet to download or make a request in android you have at your disposal many instruments. Between them the main three are :
  • Sockets
  • UrlConnection
  • HttpClient
Although, most of the times is not considered in favour of httpclient, the most useful way to handle a request with services is probably UrlConnection. UrlConnection is light, the knowledge required to use it is limited, and is powerful enough to handle a variaty of cases.
Opening and closing connections
 
//open a connection
HttpURLConnection conn = (HttpURLConnection)new URL(url).openConnection();
//Opens a communications link to the resource 
//referenced by this URL, if such a connection has not 
//already been established.

//disconnect
conn.disconnect();
//Indicates that other requests to the server are unlikely 
//in the near future.
 
Each HttpURLConnection instance is used to make a single request but the underlying network connection to the HTTP server may be transparently shared by other instances.
Calling the close() methods on the InputStream or OutputStream of an HttpURLConnection after a request may free network resources associated with this instance but has no effect on any shared persistent connection.
Calling the disconnect() method may close the underlying socket if a persistent connection is otherwise idle at that time.
URLConnection objects go through two phases: first they are created, then they are connected. After being created, and before being connected, various options can be specified
Connection timeout and read timeout
Connection timeout, in milliseconds, is the time to be used when opening a communications link to the resource referenced by this URLConnection. If the timeout expires before the connection can be established, a java.net.SocketTimeoutException is raised. A timeout of zero is interpreted as an infinite timeout.
Read timeout specifies the timeout when reading from Input stream when a connection is established to a resource. If the timeout expires before there is data available for read, a java.net.SocketTimeoutException is raised. A timeout of zero is interpreted as an infinite timeout.
Example
 
InputStream is = null;
OutputStream os = null;
HttpURLConnection conn = null;
try {
  conn = (HttpURLConnection)new URL(url).openConnection();
  conn.setConnectTimeout(connectionTimeout);
  conn.setReadTimeout(readTimeout);
  is = conn.getInputStream();
  os = new FileOutputStream(f);
  copyStream(is, os);
  os.close();
} catch (FileNotFoundException fnfe) {
  throw new ImageNotFoundException();
} catch (Exception ex) {
  Log.e(TAG, "Unknown Exception while getting the image " + ex.getMessage());
} finally {
  if(conn != null) {
    conn.disconnect();
  }
  closeSilently(is);
  closeSilently(os);
}
 
Make sure to close all the Closable resources like the InputStream. This will ensure that the the network resources can be released.
GET and POST
We have seen the get before, there is nothing special about it
 
URLConnection con = new URL(url).openConnection();
con.setRequestProperty("Accept-Charset", charset);
InputStream response = con.getInputStream();
For the post you have to specify a couple of options
URLConnection con = new URL(url).openConnection();
// Parameter that indicate a post
con.setDoOutput(true);
con.setRequestProperty("Accept-Charset", charset);
con.setRequestProperty("Content-Type", 
  "application/x-www-form-urlencoded;charset=" + charset);
...
  output = con.getOutputStream();
  output.write(query.getBytes(charset));
...
//If you use the HttpURLConnection 
HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
con.setRequestMethod("POST");
 
UrlConnection in Android
Google moving away from Apache HTTP client usage since Gingerbread.
Warning: The Android team is not actively working on Apache HTTP Client.
Known bugs
Calling close() on a readable InputStream could poison the connection pool. Work around this by disabling connection pooling:
 
private void disableConnectionReuseIfNecessary() {
    // HTTP connection reuse which was buggy pre-froyo
    if (Integer.parseInt(Build.VERSION.SDK) < Build.VERSION_CODES.FROYO) {
        System.setProperty("http.keepAlive", "false");
    }
}
 
Conclusion 
 
I think is good to reuse the conclusion from Tim Bray's article :
Important: Apache HTTP client has fewer bugs on Eclair and Froyo. It is the best choice for these releases. For Gingerbread and better, HttpURLConnection is the best choice. Its simple API and small size makes it great fit for Android. Transparent compression and response caching reduce network use, improve speed and save battery. New applications should use HttpURLConnection; it is where we will be spending our energy going forward. 
 
Officially Documentation at developer.android.com.
 
StackOverFlow Problem and Solutions.(UriConnection)
 
Share this post
  • Share to Facebook
  • Share to Twitter
  • Share to Google+
  • Share to Stumble Upon
  • Share to Evernote
  • Share to Blogger
  • Share to Email
  • Share to Yahoo Messenger
  • More...

0 comments

Thanks for your comment

:) :-) :)) =)) :( :-( :(( :d :-d @-) :p :o :>) (o) [-( :-? (p) :-s (m) 8-) :-t :-b b-( :-# =p~ :-$ (b) (f) x-) (k) (h) (c) cheer

Related Posts Plugin for WordPress, Blogger...
© Google Android Lovers
Designed by BlogThietKe Cooperated with Duy Pham
Released under Creative Commons 3.0 CC BY-NC 3.0