Android learning 20 (using HTTP to access the network)

Source: Internet
Author: User

Android learning 20 (using HTTP to access the network)

Use HttpURLConnection

There are two methods to send HTTP requests on Android: HttpURLConnection and HttpClient.
HttpURLConnection usage.
First, you need to obtain the HttpURLConnection instance. Generally, you only need to create a new URL object and input the address of the target network. Then
Call the openConnection () method as follows:
URL = new URL ("http://www.baidu.com ");
HttpURLConnection connection = (HttpURLConnection) url. openConnection ();
After obtaining the HttpURLConnection instance, we can set the method used by the HTTP request. There are two common methods,
Get and post. Get indicates that you want to obtain data from the server, while post indicates that the data is submitted to the server. The statement is as follows:
Connection. setRequestMethod ("GET ");
Next, you can customize the settings, such as setting the connection timeout, the number of milliseconds of read timeout, and the number of message headers that the server wants. This part of content is compiled according to your actual situation, for example:
Connection. setConnectionTimeout (8000 );
Connection. setReadTimeout (8000 );
Call the getInputStream () method to obtain the input stream returned by the server. The remaining task is to read the input stream, as shown below:
InputStream in = connection. getInputStream ();
Finally, you can call the disconnect () method to disable the HTTP connection, as shown below:
Connection. disconnection ();
The following uses a specific example to familiarize yourself with HttpURLConnection usage. To create a NetworkTest project, first modify the code in activit_main.xml as follows:

     
    
          
       
               
 


Because the cell phone screen space is usually relatively small, sometimes too much content can not be displayed on one screen, with the ScrollView control, you can scroll through the content outside the screen. In addition, a Button and a TextView are placed in the layout. The Button is used to send an HTTP request and the TextView is used to display the data returned by the server. Then, modify the code in MainActivity as follows:

Package com. jack. networktest; import java. io. bufferedReader; import java. io. inputStream; import java. io. inputStreamReader; import java.net. httpURLConnection; import java.net. malformedURLException; import java.net. URL; import android. annotation. suppressLint; import android. app. activity; import android. OS. bundle; import android. OS. handler; import android. OS. message; import android. util. log; import android. view. me Nu; import android. view. view; import android. view. view. onClickListener; import android. widget. button; import android. widget. textView;/* Generally, there are two methods for sending HTTP requests on Android: HttpURLConnection and HttpClient. Now, let's learn how to use HttpURLConnection. First, you need to obtain the HttpURLConnection instance. Generally, you only need to create a new URL object, input the address of the target network, and then call the openConnection () method, as shown below: URL = new URL ("http://www.baidu.com"); HttpURLConnection connection = (HttpURLConnection) url. openConnection (); after obtaining the HttpURLConnection instance, we can set the method used by the HTTP request. There are two common methods: get and post. Get indicates that you want to obtain data from the server, while post indicates that the data is submitted to the server. Statement: connection. setRequestMethod ("GET"); then you can customize it, for example, set the connection timeout, read timeout in milliseconds, and the server's desired message class. This part of content is written according to your actual situation, for example: connection. setConnectionTimeout (8000); connection. setReadTimeout (8000); then call the getInputStream () method to obtain the input stream returned by the server. The rest of the task is to read the input stream, as shown below: InputStream in = connection. getInputStream (); finally, you can call the disconnect () method to close the HTTP connection, as shown below: connection. disconnection (); the following uses a specific example to familiarize yourself with HttpURLConnection usage. Create a NetworkTest project. First, modify the code in activit_main.xml as follows: */public class MainActivity extends Activity implements OnClickListener {public static final int SHOW_RESPONSE = 0; private Button sendRequest = null; private TextView responseText = null; private Handler handler = new Handler () {@ Overridepublic void handleMessage (Message msg) {// TODO Auto-generated method stubsuper. handleMessage (msg); switch (msg. what) {case SHOW_RE Response SE: String response = (String) msg. obj; // perform the UI operation here and display the result to responseText. setText (response); break; default: break ;}};@ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); sendRequest = (Button) findViewById (R. id. send_request); responseText = (TextView) findViewById (R. id. response_text); sendRequest. setOnClickListener (this );}@ Overridepublic boolean onCreateOptionsMenu (Menu menu) {// Inflate the menu; this adds items to the action bar if it is present. getMenuInflater (). inflate (R. menu. main, menu); return true ;}@ Overridepublic void onClick (View v) {// TODO Auto-generated method stubLog. d ("MainActivity", "onClick (View v )! "); If (v. getId () = R. id. send_request) {sendRequestWithHttpURLConnection () ;}} private void sendRequestWithHttpURLConnection () {// enable the Thread to initiate a network request new Thread (new Runnable () {@ Overridepublic void run () {// TODO Auto-generated method stubHttpURLConnection connection = null; try {URL url = new URL ("http://www.baidu.com"); connection = (HttpURLConnection) url. openConnection (); connection. setRequestMethod ("GET"); connection. s EtConnectTimeout (8000); connection. setReadTimeout (8000); InputStream in = connection. getInputStream (); // read BufferedReader reader = new BufferedReader (new InputStreamReader (in) from the obtained input stream; StringBuilder response = new StringBuilder (); String line; while (line = reader. readLine ())! = Null) {response. append (line);} Message message = new Message (); message. what = SHOW_RESPONSE; // store the results returned by the server to the Message. obj = response. toString (); handler. sendMessage (message);} catch (MalformedURLException e) {// TODO Auto-generated catch blocke. printStackTrace ();} catch (Exception e) {e. printStackTrace ();} finally {if (connection! = Null) {connection. disconnect () ;}}}). start ();}}

In the send request button click event, the sendRequestWithHttpURLConnection () method is called. In this method, a subthread is enabled first, and then an HTTP request is sent using HttpURLConnection in the subthread, the target address of the request is Baidu's homepage. Then, BufferedReader is used to read the stream returned by the server, and the result is stored in a Message object. Why is the Message object used here? Of course, this is because the ui cannot be operated on in the Child thread. We want to display the content returned by the server to the interface, so we create a Message object and use Handler to send it out. Then, this Message is processed in Handler's handMessage () method, and the result is finally retrieved and set to TextView.

Before you start running, you also need to declare the network permissions. Modify the code in AndroidManifest. xml as follows:

 
     
              
                          
                                  
               
              
 


Run the program and click send request. The result is as follows:




<喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + ICAgICC3/primary + primary/secondary + G9q9Xi0Km0 + sLrveLO9rPJxq/primary + s/primary + 8/primary + 3bj4t/primary + 3dC0s/primary + vSqs/ yt/7O8cb3zOG9u9PDu6fD + 7rNw9zC66Osvs2/ydLU1eLR + dC0o7o8YnI + Signature = "POST ");
DataOutputStream out = new DataOutputStream (connection. getOutputStream ());
Out. writeBytes ("username = admin & password = 123456 ");

The above is the basic usage of HttpURLConnection. Next we will continue to explain another method.





Use HttpClient

HttpClient is an HTTP network access interface provided by Apache. It was introduced to the android api from the very beginning. It can achieve almost the same effect as HttpURLConnection, but there is a big difference between the two usage. Let's take a look at HttpClient usage. First, we need to know that HttpClient is an interface, so we cannot create its instance. Generally, we will create a DefaultHttpClient instance, as shown below: HttpClient httpClient = new DefaultHttpClient (); next, if you want to initiate a GET request, you can create an HttpGet object, input the target network address, and then call the execute () method of HttpClient: httpGet httpGet = new HttpGet ("http://www.baidu.com" without your httpclient.exe cute (httpGet); if it is a bit more complex than GET to initiate a POST request, we need to create an HttpPost object, and input the target network address, as shown below: HttpPost httpPost = new HttpPost ("http://www.baidu.com"); then store the parameters to be submitted through a NameValuePair set, and pass this set of parameters into a UrlEncodedFormEntity, and then call the setEntity () method of HttpPost to pass in the constructed UrlEncodedFormEntity, as shown below: List
 
  
Params = new ArrayList
  
   
(); Params. add (new BasicNameValuePair ("username", "jack"); params. add (new BasicNameValuePair ("password", "123456"); UrlEncodedFormEntity entity = new UrlEncodedFormEntity (params, "UTF-8"); httpPost. setEntity (entity); the next operation is the same as HttpGet. Call the execute () method of HttpClient and pass in the HttpPost object to: httpClient.exe cute (httpPost); execute () then, an HttpResponse object is returned, and all the information returned by the server is included in this object. Generally, the status code returned by the server is retrieved first. if the value is 200, the request and response are successful, as shown in the following code: if (httpResponse. getStatusCode () = 200) {// the request and response are successful} next, retrieve the specific content returned by the Service in the internal part of the if judgment. You can call getEntity () method to obtain an HttpEntity instance, and then use EntityUtils. toString () This static method converts HttpEntity into a string, as shown below: HttpEntity entity = httpResponse. getEntity (); String response = EntityUtils. toString (entity); note that if the data returned by the server contains Chinese characters, you can directly call EntityUtils. if the toString () method is converted with garbled characters, you only need to specify the character set to UTF-8 during the conversion, as shown in the following figure: String response = EntityUtils. toString (entity, "UTF-8 ");
  
 

HttpClient is an HTTP network access interface provided by Apache. It was introduced to the android api from the very beginning. It can
The result is almost the same as that of HttpURLConnection, but there is a big difference between the two. Let's take a look at HttpClient usage.
First, we need to know that HttpClient is an interface, so we cannot create its instance. Generally, we will create a DefaultHttpClient instance, as shown below:
HttpClient httpClient = new DefaultHttpClient ();
Next, if you want to initiate a GET request, you can create an HttpGet object, input the target network address, and then call the execute () method of HttpClient:
HttpGet httpGet = new HttpGet ("http://www.baidu.com ");
HttpClient.exe cute (httpGet );
If a POST request is initiated, it is a little more complex than GET. We need to create an HttpPost object and input the target network address, as shown below:
HttpPost httpPost = new HttpPost ("http://www.baidu.com ");
Then, a NameValuePair set is used to store the parameters to be submitted, and the set is passed into a UrlEncodedFormEntity. Then
Call the setEntity () method of HttpPost to pass in the constructed UrlEncodedFormEntity, as shown below:
List Params = new ArrayList ();
Params. add (new BasicNameValuePair ("username", "jack "));
Params. add (new BasicNameValuePair ("password", "123456 "));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity (params, "UTF-8 ");
HttpPost. setEntity (entity );
The next operation is the same as HttpGet. Call the execute () method of HttpClient and pass in the HttpPost object:
HttpClient.exe cute (httpPost );
After the execute () method is executed, an HttpResponse object is returned, and all information returned by the server is included in this object. Normally, the status returned by the server is retrieved first.
If it is 200, the request and response are successful, as shown below:
If (httpResponse. getStatusCode () = 200 ){

// The request and response are successful.
}
Next, retrieve the specific content returned by the Service in the if judgment. You can call the getEntity () method to obtain an HttpEntity instance, and then use
EntityUtils. toString () This static method converts HttpEntity into a string, as shown below:
HttpEntity entity = httpResponse. getEntity ();
String response = EntityUtils. toString (entity );
Note: If the data returned by the server contains Chinese characters, it is garbled to directly call EntityUtils. toString () for conversion.
You only need to specify the character set as UTF-8 during conversion, as shown below:
String response = EntityUtils. toString (entity, "UTF-8 ");





Next, use the NetworkTest project to HttpClient.

The layout does not need to be changed at all, so now you can directly modify the code in MainActivity, as shown below:

Package com. jack. networktest; import java. io. bufferedReader; import java. io. IOException; import java. io. inputStream; import java. io. inputStreamReader; import java.net. httpURLConnection; import java.net. malformedURLException; import java.net. URL; import org. apache. http. httpEntity; import org. apache. http. httpHost; import org. apache. http. httpRequest; import org. apache. http. httpResponse; import org. apache. http. cli Ent. clientProtocolException; import org. apache. http. client. httpClient; import org. apache. http. client. responseHandler; import org. apache. http. client. methods. httpGet; import org. apache. http. client. methods. httpUriRequest; import org. apache. http. conn. clientConnectionManager; import org. apache. http. impl. client. defaultHttpClient; import org. apache. http. params. httpParams; import org. apache. http. protocol. httpCont Ext; import org. apache. http. util. entityUtils; import android. annotation. suppressLint; import android. app. activity; import android. OS. bundle; import android. OS. handler; import android. OS. message; import android. util. log; import android. view. menu; import android. view. view; import android. view. view. onClickListener; import android. widget. button; import android. widget. textView; public class MainActivity extends Act Ivity implements OnClickListener {public static final int SHOW_RESPONSE = 0; private Button sendRequest = null; private TextView responseText = null; private Handler handler = new Handler () {@ Overridepublic void handleMessage (Message msg) {// TODO Auto-generated method stubsuper. handleMessage (msg); switch (msg. what) {case SHOW_RESPONSE: String response = (String) msg. obj; // perform the UI operation here and display the result to responseText. setText (res Ponse); break; default: break ;}};@ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); sendRequest = (Button) findViewById (R. id. send_request); responseText = (TextView) findViewById (R. id. response_text); sendRequest. setOnClickListener (this) ;}@ Overridepublic boolean onCreateOptionsMenu (Menu menu) {// Inflate the menu; this adds Items to the action bar if it is present. getMenuInflater (). inflate (R. menu. main, menu); return true ;}@ Overridepublic void onClick (View v) {// TODO Auto-generated method stubLog. d ("MainActivity", "onClick (View v )! "); If (v. getId () = R. id. send_request) {// sendRequestWithHttpURLConnection (); sendRequestWithHttpClient () ;}} private void sendRequestWithHttpURLConnection () {// enable the Thread to initiate a network request new Thread (new Runnable () {@ Overridepublic void run () {// TODO Auto-generated method stubHttpURLConnection connection = null; try {URL url = new URL ("http://www.baidu.com"); connection = (HttpURLConnection) url. openConnection (); connection. setReq UestMethod ("GET"); connection. setConnectTimeout (8000); connection. setReadTimeout (8000); InputStream in = connection. getInputStream (); // read BufferedReader reader = new BufferedReader (new InputStreamReader (in) from the obtained input stream; StringBuilder response = new StringBuilder (); String line; while (line = reader. readLine ())! = Null) {response. append (line);} Message message = new Message (); message. what = SHOW_RESPONSE; // store the results returned by the server to the Message. obj = response. toString (); handler. sendMessage (message);} catch (MalformedURLException e) {// TODO Auto-generated catch blocke. printStackTrace ();} catch (Exception e) {e. printStackTrace ();} finally {if (connection! = Null) {connection. disconnect ();}}}}). start ();} private void sendRequestWithHttpClient () {new Thread (new Runnable () {@ Overridepublic void run () {// TODO Auto-generated method stubtry {HttpClient httpClient = new DefaultHttpClient (); HttpGet httpGet = new HttpGet ("http://www.baidu.com"); HttpResponse route cute (httpGet); if (httpResponse. getStatusLine (). getStatusCode () = 200) {// the request and response are successful. HttpEntity entity = httpResponse. getEntity (); String response = EntityUtils. toString (entity, "UTF-8"); Message message = new Message (); message. what = SHOW_RESPONSE; // store the results returned by the server to the Message. obj = response. toString (); handler. sendMessage (message) ;}} catch (Exception e) {e. printStackTrace ();}}}). start ();}}

The above Code only adds a sendRequestWithHttpClient () method, and calls this method in the send request button click event. In this method, a sub-thread is also enabled first, and then an HTTP request is sent using HttpClient in the sub-thread. The target address of the request is the Baidu homepage. Store the data returned by the server to the Message object and send the Message with Handler.

Now run the program again and click the send request button. You will find the same result as above. This proves that the Http request sending function using HttpClient has also been implemented.


After the above exercises, we should know the basic usage of HttpURLConnection and HttpClient almost.

Http://blog.csdn.net/j903829182/article/details/42440155



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.