"Turn" Pro Android Learning note (six or seven): HTTP service (1): HTTP GET

Source: Internet
Author: User
Tags http 200 http post

Directory (?) [-]

    1. HTTP Get Small Example
      1. Simple Small Example
      2. An exception occurred networkonmainthreadexception
      3. Processing through Strictmode
      4. URL with key-value pairs

Andriod apps can take advantage of the service to provide many features, such as leveraging the Google Maps API, and now we'll focus on HTTP Serice.

The Android SDK provides httpclient, which is very similar to the interface in the Java EE. The most common is HTTP GET and HTTP POST. You can also read the Android Learning Note (four or five): Internet communication-httpclient, XML parsing.

HTTP Get Small Example

Because you want to access the Internet, you should add Android.permission.INTENT permissions to the Andriodmanifest.xml file.

Simple Small Example

The small example is simple, send an HTTP Get, request to open a URL, and print the HTTP response you received via log.

public class Httpgetdemo extends activity{
@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);

BufferedReader in = null;
try{
//"Step 1" to create an HttpClient object (or use an existing one)
HttpClient client = new Defaulthttpclient ();
"Step 2" instantiates an HTTP GET or HTTP POST, this example is an HTTP GET
HttpGet request = new HttpGet ("
Http://www.baidu.com");
"Step 3" sets the HTTP parameter, this example is the simplest to open a URL of HTTP GET, without setting
"Step 4" to execute HTTP call via HttpClient (HTTP request issued)
HttpResponse response = Client.execute (request);

//"Step 5" handles the HTTP response, in this case the contents of the entire response (the body of the HTTP 200 message) are in string.
In = new BufferedReader (
New InputStreamReader (
Response.getentity (). GetContent ())
);
StringBuffer buff = new StringBuffer ("");
String line = "";
String NL = System.getproperty ("Line.separator"); It's actually "\ n", which automatically fits the system's line break.
while (line = In.readline ()) = null) {
Buff.append (line + NL);
}
In.close ();
LOG.D ("PRO", buff.tostring ());
}catch (Exception e) {
E.printstacktrace ();
LOG.D ("PRO", e.tostring ());
}finally{Finally,//try{}catch () {}finally{} is slightly less, but useful, and will execute the finally code, usually in Xx.close (), whether or not there is an exception.
if (in = null) {
try{
in.close ();//Close BufferedReader, and also turn off the underlying HTTP connection
}catch (Exception e) {
E.printstacktrace ();
LOG.D ("PRO", "Error in finally:\n" + e.tostring ());
}
}
}
}

}

An exception occurred networkonmainthreadexception

This is a very simple example, but the error when running:

The example is simple, the code has nothing to question, why? According to the documentation, this error occurs when the application attempts to perform a network operation in the main thread (main), only in the Honeycomb SDK or later. That is, in Android 3.0 and later, if the main thread for network access, will throw out networkonmainthreadexception. While checking the Androidmanifest.xml file, found:

<uses-sdk android:minsdkversion= ".../>

This is the version that runs on Android 4.0 and above. Android 3.0 corresponds to API level 10, we simply change to:

<USES-SDK android:minsdkversion= "9"/>

It makes sense to do this with Android, and we notice a line in the code:

/* Establish a TCP connection for HTTP (including previous DNS resolution for URLs), send an HTTP GET request, and wait for an HTTP response message. This statement executes too much content, and some steps may cause a long wait for network problems to connect to (or eventually not connect) the site. Therefore, the execution time of this statement can be very long, it is recommended to be in the thread for background processing, rather than the main thread (also the UI thread), otherwise the activity due to the execution of the statement caused by the UI unresponsive problem. In addition, if the Web page is large and needs to be read for a long time, the main thread will cause the UI to be unresponsive due to execution of the statement (I'm not sure if the Read page is read in Execute, or as a stream in the back in, but I tend to read it in Execute, Because the HttpResponse object has been acquired)* /
HttpResponse response = Client.execute (request);

Processing through Strictmode

The reasonable treatment of networkonmainthreadexception is to place network access in the thread, this example is placed directly in the activity in order to demonstrate, under normal circumstances, should not be treated as such.

To avoid exceptions while processing the Modify API level, you also need to specify a minimum run version of Android 3.0 above, for example This example initially specifies android:minsdkversion= "14". You can also do the following with your code:

......
Strictmode.threadpolicy policy = new StrictMode.ThreadPolicy.Builder (). Permitall (). build ();
Strictmode.setthreadpolicy (Policy);
......
BufferedReader in = null;
Try{...} catch (Exception e) {...} Finally{...}

Strictmode us in Pro Android Learning Note (55): Debug and Analysis (3): ADB command, simulator console and Strictmode introduced, do not prohibit the running of certain policies of the thread, the above code does not do any policy checks, of course, can only release the network, That is, you can also use Permitnetwork ().

Related reference bug handling can be found in: http://www.lucazanini.eu/2012/android/the-android-os-networkonmainthreadexception-exception/?lang=en

Of course, we should understand that try not to have network access code in activity (main thread).

URL with key-value pairs

For Cgi,url is a key-value pair, the most common is the search site, the site based on the information carried by the URL to determine what the user is searching for. For example:

HttpClient client = new Defaulthttpclient ();
HttpGet request = new HttpGet ("http://www.google.com.hk/#newwindow =1&q=android&safe=strict");
HttpResponse response = Client.execute (request);

More can use the HTTP POST method, we will continue to learn.

The example code covered in this blog post can be downloaded in the Pro Android Learning: Http Service Small example.

RELATED Links: My Android development related articles

"Turn" Pro Android Learning note (six or seven): HTTP service (1): HTTP GET

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.