1.1. Available API’s
Android contains the standard Java network java.net
package which can be used to access network resources. Android also contains the Apache HttpClient library.
The base class for HTTP network access in the java.net
package is that HttpURLConnection
class .
It used to be that the preferred access of the network would be the Apache HttpClient library. September 2011 the Android development team published a blog entry in which they suggest to prefer HttpURLConnection
in future Android projects as they constantly improving this implementation.
To access the Internet your application requires the android.permission.INTERNET
permission.
Within Android development you should avoid performing long running operations on the UI thread. This includes file and network access. StrictMode
allows to setup policies in your application to avoid doing incorrect things. As of Android 3.0 (Honeycomb) StrictMode
is configured to crash with an NetworkOnMainThreadException
exception if network access happens in the UI thread.
While you should do network access in a background thread this tutorial will avoid this to allow the user to learn network access independent from background processing.
If you targeting Android 3.0 or higher you can turn this check of via the following code at beginning of your onCreate()
method of your Activity
.
StrictMode.ThreadPolicy policy = new StrictMode. ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy);
HttpURLConnection
is a general-purpose, lightweight HTTP client suitable for most applications. This API is recommended by the Android development team to use in newer applications, as this interface get constantly improved.
In the latest version HttpURLConnection
supports transparent response compression (via the header Accept-Encoding: gzip
, Server Name Indication (extension of SSL and TLS) and a response cache.
The API is relatively straigh forward. For example to retrieve the webpage http://www.vogella.de.
URL url = new URL("http://www.vogella.de/"); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); try { InputStream in = new BufferedInputStream(urlConnection.getInputStream()); readStream(in); finally { urlConnection.disconnect(); } }
Android contains the Apache HttpClient library. You can either use the DefaultHttpClient
or AndroidHttpClient
to setup the HTTP client.
DefaultHttpClient
is the standard HttpClient and uses the SingleClientConnManager
class to handle HTTP connections. SingleClientConnManager
is not thread-safe, this means that access to it via several threads will create problems.
The following is an example an HTTP Get request via HttpClient
.
HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet("http://www.vogella.de"); HttpResponse response = client.execute(request); // Get the response BufferedReader rd = new BufferedReader(new InputStreamReader( response.getEntity().getContent())); String line = ""; while ((line = rd.readLine()) != null) { textView.append(line); }
AndroidHttpClient
is a special implementation of DefaultHttpClient
which is pre-configured for Android.
AndroidHttpClient
was introduced in Android 2.2. An instance can be received via the newInstance()
method which allows to specify the user agent as parameter. AndroidHttpClient supports SSL and has utility methods for GZIP compressed data. It registers the ThreadSafeClientConnManager
which allows thread safe HTTP access via a managed connection pool. AndroidHttpClient
also applied reasonable default for timeouts and socket buffer sizes. It also supports HTTPS by default.
Create the project de.vogella.android.network.html
with the activity ReadWebpage
. Change the layout main.xml
to the following.
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <LinearLayout android:id="@+id/LinearLayout01" android:layout_width="wrap_content" android:layout_height="wrap_content" > </LinearLayout> <EditText android:id="@+id/address" android:layout_width="fill_parent" android:layout_height="wrap_content" > </EditText> <Button android:id="@+id/ReadWebPage" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="myClickHandler" android:text="Read Webpage" > </Button> <TextView android:id="@+id/pagetext" android:layout_width="fill_parent" android:layout_height="fill_parent" android:scrollbars="vertical" > </TextView> </LinearLayout>
Add the permission android.permission.INTERNET
to the AndroidManifest.xml
file to allow your application to access the Internet.
Create the following code to read a webpage and show the HTML code in the TextView.
This example also demonstrate the usage of Android preferences to store user data. The URL which the user has typed is stored in the preferences in the onPause()
method. This method is called whenever the Activity
is send into the background.
package de.vogella.android.network.html; import java.io.BufferedReader; import java.io.InputStreamReader; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import android.app.Activity; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.TextView; public class ReadWebpage extends Activity { private static final String PREFERENCES = "PREFERENCES"; private static final String URL = "url"; private String lastUrl; private EditText urlText; private TextView textView;
@Overridepublic void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); urlText = (EditText) findViewById(R.id.address); textView = (TextView) findViewById(R.id.pagetext); loadPreferences(); urlText.setText(lastUrl); }
private void loadPreferences() { SharedPreferences preferences = getSharedPreferences(PREFERENCES, Activity.MODE_PRIVATE); // Set this to the Google Homepage lastUrl = preferences.getString(URL, "http://209.85.229.147"); } @Override protected void onPause() { super.onPause(); SharedPreferences preferences = getSharedPreferences(PREFERENCES, Activity.MODE_PRIVATE); Editor preferenceEditor = preferences.edit(); preferenceEditor.putString(URL, urlText.getText().toString()); // You have to commit otherwise the changes will not be remembered preferenceEditor.commit(); } public void myClickHandler(View view) { switch (view.getId()) { case R.id.ReadWebPage: try { textView.setText(""); HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(urlText.getText().toString()); HttpResponse response = client.execute(request); // Get the response BufferedReader rd = new BufferedReader(new InputStreamReader( response.getEntity().getContent())); String line = ""; while ((line = rd.readLine()) != null) { textView.append(line); } } catch (Exception e) { System.out.println("Nay, did not work"); textView.setText(e.getMessage()); } break; } } }
Obviously the network on an Android device is not always available. You can check the network is currently available via the following code. This requires the ACCESS_NETWORK_STATE
permission.
public boolean isNetworkAvailable() { ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = cm.getActiveNetworkInfo(); // if no network is available networkInfo will be null, otherwise check if we are connected if (networkInfo != null && networkInfo.isConnected()) { return true; } return false; }
This chapter is only relevant for you if you are testing with the Android similator behind a proxy. In class you are behind a proxy during your testing you can set the proxy via the class “Settings”. For example you could add the following line to your onCreate method in your activity.
Settings.System.putString(getContentResolver(), Settings.System.HTTP_PROXY, "myproxy:8080");
To change the proxy settings you have to have the permission “android.permission.WRITE_SETTINGS” in “AndroidManifest.xml”.
Tip
It seems that DNS resolving doesn’t work behind a proxy. See Bug 2764
Network connection fail frequently especially for mobile clients. For example if you switch from Wifi to 3G then an existing network connection will break and you need to retry the request.
The Apache HttpClient has an default DefaultHttpRequestRetryHandler
object registered which will per default 3 times retry a failed connection. The problem is that switching from one network to another make take a little while and DefaultHttpRequestRetryHandler
will retry immediately.
To work around this issue you can implement your own version of DefaultHttpRequestRetryHandler
in which you wait a pre-defined time.
For example the implementation could look like:
AbstractHttpClient client = (AbstractHttpClient) new DefaultHttpClient(); DefaultHttpRequestRetryHandler retryHandler = new DefaultHttpRequestRetryHandler() { @Override public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { if (!super.retryRequest(exception, executionCount, context)) { return false; } // Retry but wait a bit try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } return true; } }; client.setHttpRequestRetryHandler(retryHandler);
Great post, I believe blog owners should acquire a lot from this weblog its real user genial. So much excellent information on here :D.
LikeLike
Very interesting info!Perfect just what I was looking for!
LikeLike
I like this blog very much so much fantastic information. “The great thing about democracy is that it gives every voter a chance to do something stupid.” by Art Spander.
LikeLike
I was recommended this web site via my cousin. I’m no longer sure whether this post is written by him as no one else recognize such designated approximately my trouble. You’re incredible! Thank you!
LikeLike
Just a smiling visitant here to share the love (:, btw great pattern. “The price one pays for pursuing a profession, or calling, is an intimate knowledge of its ugly side.” by James Arthur Baldwin.
LikeLike
I am now not positive where you are getting your info, however great topic. I needs to spend some time learning much more or figuring out more. Thanks for excellent info I used to be on the lookout for this info for my mission.
LikeLike
I like this web site very much so much excellent information.
LikeLike
Very nice layout and superb subject matter, very little else we want :D.
LikeLike
I know this if off topic but I’m looking into starting my own weblog and was curious what all is needed to get setup? I’m assuming having a blog like yours would cost a pretty penny? I’m not very web smart so I’m not 100% positive. Any recommendations or advice would be greatly appreciated. Thanks
LikeLike
cheers for taking the time to discuss this, I feel strongly about it and adore learning a lot more on this topic. If possible, as you gain expertise, could you mind updating your blog with more information? as it is incredibly helpful for me.
LikeLike
I am glad to be a visitor of this pure web site, regards for this rare information!
LikeLike
You have remarked very interesting points! ps nice website.
LikeLike
Just wanna remark on few general things, The website layout is perfect, the content is very superb. “The way you treat yourself sets the standard for others.” by Sonya Friedman.
LikeLike
I regard something really special in this website.
LikeLike
Hmm is anyone else encountering problems with the images on this blog loading? I’m trying to determine if its a problem on my end or if it’s the blog. Any responses would be greatly appreciated.
LikeLike
I really like your writing style, great information, thankyou for posting : D.
LikeLike
Excellent site you have here but I was wanting to know if you knew of any user discussion forums that cover the same topics discussed here? I’d really love to be a part of community where I can get suggestions from other experienced people that share the same interest. If you have any recommendations, please let me know. Bless you!
LikeLike
oh my god fantastic article admin will test your blog site usually
LikeLike
Very interesting information!Perfect just what I was looking for! “Neurotics build castles in the air, psychotics live in them. My mother cleans them.” by Rita Rudner.
LikeLike
Some really excellent information, Sword lily I discovered this. “I have hardly ever known a mathematician who was capable of reasoning.” by Plato.
LikeLike
Nice post . keep up to date the best work And like most people, you probably do not have the expertise to eradicate said virus, making trojan removal about as big a reach as, say, fixing your transmission or tailoring a suit.
LikeLike
Hey, you used to write wonderful, but the last several posts have been kinda boringÖ I miss your great writings. Past several posts are just a little out of track! come on!
LikeLike
Outstanding post, I conceive people should learn a lot from this web site its very user friendly. So much good information on here :D.
LikeLike
I dugg some of you post as I cerebrated they were very beneficial handy
LikeLike
Really excellent information can be found on web blog .
LikeLike
Woh I enjoy your articles , saved to favorites ! .
LikeLike
Thank you for helping out, fantastic info. “Job dissatisfaction is the number one factor in whether you survive your first heart attack.” by Anthony Robbins.
LikeLike
Simply wish to say your own article is as incredible. The clarity for your put up is simply great and that i could presume you’re a professional with this subject. Well together with your permission allow me to snatch your feed to remain up to date with approaching post. Thank you a million and please continue the rewarding work.
LikeLike
Youre so right. Im there with you. Your blog post is definitely worth a read if anyone comes throughout it. Im lucky I did so because now Ive obtained a whole new take a look at this. I didnt realise until this issue was so important and thus universal. You undoubtedly stick it in perspective to me.
LikeLike
Great post, I think blog owners should acquire a lot from this web site its really user genial. So much excellent info on here :D.
LikeLike
Valuable information. Lucky me I discovered your web site unintentionally, and I am shocked why this twist of fate did not came about earlier! I bookmarked it.
LikeLike
Thank you for the sensible critique. Me and my neighbor were just preparing to do some research about this. We got a grab a book from our area library but I think I learned more from this post. I am very glad to see such fantastic information being shared freely out there.
LikeLike
I know this if off topic but I’m looking into starting my own weblog and was wondering what all is required to get setup? I’m assuming having a blog like yours would cost a pretty penny? I’m not very internet savvy so I’m not 100% certain. Any recommendations or advice would be greatly appreciated. Thank you
LikeLike
Hey…this is a wonderful website buddy!!! i am new here and i found this site very interesting and informative ,, you are a professional blogger…thank you for the post buddy and keep on posting nice stuff like this…and hat off to your work
LikeLike
Appreciating the dedication you put into your site and detailed information you provide. It’s good to come across a blog every once in a while that isn’t the same unwanted rehashed information. Wonderful read! I’ve saved your site and I’m including your RSS feeds to my Google account.
LikeLike
Very nice style and design and wonderful content material, very little else we require :D.
LikeLike
Hmm it appears like your site ate my first comment (it was super long) so I guess I’ll just sum it up what I had written and say, I’m thoroughly enjoying your blog. I too am an aspiring blog writer but I’m still new to the whole thing. Do you have any helpful hints for novice blog writers? I’d really appreciate it.
LikeLike
Some genuinely quality posts on this internet site , bookmarked .
LikeLike
I always was interested in this topic and still am, regards for putting up.
LikeLike