Android Learning 20 (using the HTTP protocol to access the network)

Source: Internet
Author: User

Using HttpURLConnection

There are generally two ways to send HTTP requests on Android, HttpURLConnection and HttpClient, and now learn the next
The use of httpurlconnection.
First, you need to obtain an instance of HttpURLConnection, typically just a new URL object, and pass in the address of the destination network, and then
Call the OpenConnection () method as follows:
URL url=new url ("http://www.baidu.com");
HttpURLConnection connection= (httpurlconnection) url.openconnection ();
Once we get an example of httpurlconnection, we can set the method used by the HTTP request. There are two main methods used,
Get and post. Get indicates that you want to fetch data from the server, while post indicates that the data is submitted to the server. The wording is as follows:
Connection.setrequestmethod ("GET");
The next step is to make some free customizations, such as setting the connection timeout, the number of milliseconds to read the timeout, and some of the messages the server wants to receive first. This section is written according to your actual situation, with the following examples:
Connection.setconnectiontimeout (8000);
Connection.setreadtimeout (8000);
The getInputStream () method is then called to fetch the input stream returned by the server, and the remaining task is to read the input stream as follows:
InputStream In=connection.getinputstream ();
Finally, you can call the disconnect () method to close the HTTP connection as follows:
Connection.disconnection ();
Below is a concrete example to familiarize yourself with the usage of the httpurlconnection. To create a new Networktest project, first modify the code in the Activit_main.xml as follows:

<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android"    xmlns:tools= "http// Schemas.android.com/tools "    android:layout_width=" match_parent "    android:layout_height=" Match_parent "    android:orientation= "vertical"    >    <button         android:id= "@+id/send_request"        android: Layout_width= "Match_parent"        android:layout_height= "wrap_content"        android:text= "send Request"        />  <scrollview         android:layout_width= "match_parent"        android:layout_height= "Match_parent        " >        <textview             android:id= "@+id/response_text"            android:layout_width= "Match_parent            " android:layout_height= "Wrap_content"            />    </ScrollView>             </LinearLayout>


because the cell phone screen space is generally relatively small, sometimes too much content one screen is not displayed, with the help of the ScrollView control can allow us to scroll to see the content of the outside of the screen. In addition, a button and a Textview,button are placed in the layout to send HTTP requests, and TextView is used to display the data returned by the server. Then modify the code in the 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.menu;import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.button;import android.widget.textview;/* the way to send HTTP requests on Android generally have two kinds, httpurlconnection and httpclient, now learn the use of httpurlconnection. First, you need to obtain an instance of HttpURLConnection, generally simply new out of a URL object, and the address of the destination network, and then call the OpenConnection () method, as follows: URL url=new url ("http/ Www.baidu.com "); HttpURLConnection connection= (httpurlconnection) url.openconnection (); Once we get an example of httpurlconnection, we can set the method used by the HTTP request. There are two main methods, get and post. Get indicates that you want to fetch data from the server, while post indicates that the data is submitted to the server. The wording is as follows: Connection.setrequestmethod ("GET"); The next step is to make some free customizations, such as setting the connection timeout, the number of milliseconds to read the timeout,And some messages that the server wants to get first class. This part of the content according to their actual situation to write, examples are as follows: Connection.setconnectiontimeout (8000); Connection.setreadtimeout (8000); The getInputStream () method is then called to fetch the input stream returned by the server, and the remaining task is to read the input stream as follows: InputStream In=connection.getinputstream (); Finally, you can call the disconnect () method to close the HTTP connection as follows: Connection.disconnection (); Below is a concrete example to familiarize yourself with the usage of the httpurlconnection. To create a new 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_response:string response= (String) msg.obj;// The UI operation is performed here, the results are displayed on the interface 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 PR Esent.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 () {///Open thread initiating 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.setconnecttimeout (8000); Connection.setreadtimeout (8000); InputStream In=connection.getinputstream (); /down face gets to the input stream to read BufferedReader reader=new BufferedReader (New InputStreamReader (in)); StringBuilder response=new StringBuilder (); String Line;while ((Line=reader.readline ())!=null) {response.append (line);} Message message=new message (); message.what=show_response;//stores the results returned by the server in Message 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 ();}}

The sendrequestwithhttpurlconnection () method is called in the Click event of the Send Request button, in which a child thread is first opened and then used in the child threadHttpURLConnection issued an HTTP request, the target address of the request is Baidu's homepage. The stream returned by the server is then read with BufferedReader and the result is stored in a message object. Why do we use the message object here? Of course, because the UI cannot be manipulated in a child thread. We want to be able to display the content returned by the server to the interface, so we create a message object and send it out using handler. This message is then processed in Handler's Handmessage () method, and the result is finally fetched and set to TextView.

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

<?xml version= "1.0" encoding= "Utf-8"? ><manifest xmlns:android= "http://schemas.android.com/apk/res/ Android "package=" Com.jack.networktest "android:versioncode=" 1 "android:versionname=" 1.0 "> <uses-permis Sion android:name= "Android.permission.INTERNET"/> <uses-sdk android:minsdkversion= "Android" oid:targetsdkversion= "/> <application android:allowbackup=" true "android:icon=" @drawable/ic_lau            Ncher "android:label=" @string/app_name "android:theme=" @style/apptheme "> <activity Android:name= "com.jack.networktest.MainActivity" android:label= "@string/app_name" > <intent-fi lter> <action android:name= "Android.intent.action.MAIN"/> <category Android:nam E= "Android.intent.category.LAUNCHER"/> </intent-filter> </activity> </application& Gt;</manifest>


Run the next program, click the Send Request button, and the results are as follows:




This HTML code is returned to us by the server, but usually the browser parses the code into a beautiful web page and displays it.

if you want to submit data to the server, simply change the method of the HTTP request to post and write out the data to be submitted before fetching the input stream. Note that each data must be in the form of a key-value pair, the data and data are separated by A & symbol, for example, we want to submit a user name and password to the server, you can write:
Connection.setrequestmethod ("POST");
DataOutputStream out=new DataOutputStream (Connection.getoutputstream ());
Out.writebytes ("username=admin&password=123456");

The above is the basic use of httpurlconnection, the following continue to explain another method.





Using HttpClient

<span style= "FONT-SIZE:18PX;" > HttpClient is an Apache-provided HTTP network access interface that was introduced to the Android API from the very beginning.    It can accomplish almost exactly the same effect as httpurlconnection, but there is a big difference between the two, so let's look at the usage of httpclient. First we need to know that HttpClient is an interface and therefore cannot create an instance of it, and typically creates an instance of Defaulthttpclient, as follows: HttpClient httpclient=new Defaulthttpclient (); Next, if you want to initiate a GET request, you can create a HttpGet object, pass in the destination's network address, and then call the Execute () method of httpclient: HttpGet httpget= New HttpGet ("http://www.baidu.com"); Httpclient.execute (httpget); If initiating a POST request is slightly more complicated than get, we need to create a HttpPost object,  and pass in the destination network address as follows: HttpPost httppost=new httppost ("http://www.baidu.com"); A Namevaluepair collection is then held to hold the arguments to be submitted, and the collection of parameters is passed into a urlencodedformentity, and then the Setentity () of HttpPost is called.  The Urlencodedformentity method passes the built-in input as follows: List<namevaluepair> params=new arraylist<namevaluepair> ();  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, calling HTTPCLIent the Execute () method, and the HttpPost object is passed in: Httpclient.execute (HttpPost); After executing the Execute () method, a HttpResponse object is returned, and all the information returned by the server is included in the face. Usually we will first take out the status code returned by the server, if equal to 200 indicates that the request and response are successful, as follows: if (Httpresponse.getstatuscode () ==200) {//Request and response all succeeded} next in this if judgment  The internal FETCH service returns the specific content, you can call the GetEntity () method to get to a httpentity instance, and then use Entityutils.tostring () This static method to convert Httpentity to a string, as follows:  Httpentity entity=httpresponse.getentity ();  String response=entityutils.tostring (entity); Note If the data returned by the server is in Chinese, the direct call to the Entityutils.tostring () method for conversion will be garbled, this time only need to specify the character set as Utf-8 when converting, as follows: String response= Entityutils.tostring (Entity, "Utf-8");</span>

HttpClient is an HTTP network access interface provided by Apache, which was introduced into the Android API from the very beginning. It can be
Complete and httpurlconnection almost exactly the same effect, but the usage between the two has a larger difference, let's look at the use of httpclient.
First we need to know that httpclient is an interface and therefore cannot create an instance of it, and typically creates an instance of Defaulthttpclient, as follows:
HttpClient httpclient=new defaulthttpclient ();
Next, if you want to initiate a GET request, you can create a HttpGet object, pass in the destination's network address, and then call the HttpClient Execute () method:
HttpGet httpget=new httpget ("http://www.baidu.com");
Httpclient.execute (HttpGet);
If initiating a POST request is slightly more complicated than get, we need to create a HttpPost object and pass in the destination network address as follows:
HttpPost httppost=new httppost ("http://www.baidu.com");
A Namevaluepair collection is then held to hold the arguments to be submitted, and the collection of parameters is passed into a urlencodedformentity, and then
Call HttpPost's Setentity () method to pass the built-in urlencodedformentity as follows:
List<namevaluepair> params=new arraylist<namevaluepair> ();
Params.add (New Basicnamevaluepair ("username", "Jack"));
Params.add (New Basicnamevaluepair ("Password", "123456"));
Urlencodedformentity entity=new urlencodedformentity (params, "utf-8");
Httppost.setentity (entity);
The next action is the same as HttpGet, calling the Execute () method of HttpClient and passing the HttpPost object in:
Httpclient.execute (HttpPost);
After executing the Execute () method, a HttpResponse object is returned, and all the information returned by the server is included in the face. Normally we'll take out the state returned by the server.
The code, if equal to 200, indicates that the request and response were successful, as follows:
if (Httpresponse.getstatuscode () ==200) {

Both the request and the response were successful.
}
Next, in this if judgment of the internal fetch service return the specific content, you can call the GetEntity () method to get to a httpentity instance, and then use the
Entityutils.tostring () This static method converts httpentity into a string, as follows:
Httpentity entity=httpresponse.getentity ();
String response=entityutils.tostring (entity);
Note If the data returned by the server is in Chinese, the direct call to the Entityutils.tostring () method will appear garbled, this time
You only need to specify the character set as Utf-8 when converting, as follows:
String response=entityutils.tostring (Entity, "utf-8");





Next, Networktest this project to HttpClient way to achieve again.

The layout section does not have to be changed at all, so now directly modify the code in Mainactivity as follows:

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.client.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.httpcontext;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 AndroidOid.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 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_response:string response= (String) msg.obj;// The UI operation is performed here, the results are displayed on the interface 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 (); Sendrequestwithhttpclient ();}} private void Sendrequestwithhttpurlconnection () {///Open thread initiating 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.setconnecttimeout (8000); Connection.setreadtimeout (8000); InputStream In=connection.getinputstream (); /down face gets to the input stream to read BufferedReader reader=new BufferedReader (New InputStreamReader (in)); StringBuilder response=new StringBuilder (); String Line;while ((Line=reader.readline ())!=null) {response.append (line);} Message message=new message (); message.what=show_response;//The results returned by the server are stored in message 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 Httpresponse=httpclient.execute (HttpGet); if (Httpresponse.getstatusline (). GetStatusCode () ==200) {// Both the request and the response were successful httpentity entity=httpresponse.getentity (); String response=entityutils.tostring (Entity, "utf-8"); Message message=new message (); message.what=show_response;//stores the results returned by the server in Message message.obj=response.tostring (); Handler.sendmessage (message);}} catch (Exception e) {e.printstacktrace ();}}}). Start ();}}

The code above simply adds a sendrequestwithhttpclient () method and calls the method in the Click event of the Send Request button. In this method is also the first to open a child thread, and then use httpclient in the child thread to send an HTTP request, the target address of the request or Baidu's homepage. The data returned by the server is then stored in the Message object, and the message is sent with handler.

Now rerun the program, click the Send Request button, and you will find the same results as above, which proves that the ability to use HttpClient to send HTTP requests has also been implemented.


After the above practice, the basic usage of httpurlconnection and httpclient should be mastered almost.

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



Android Learning 20 (using the HTTP protocol to access the network)

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.