Go deep into Android and access HTTP resources through Apache HTTP
Httpclient Interface
Implementation class: defaulthttpclient, which is also a common subclass used to implement the httpclient interface,
Common abstract methods defined in httpclietnt
Method Name |
Description |
Public abstract httpresponse execute (httpurirequest request) |
An httpresponse object is returned after the httpurirequest object is executed. |
Public abstract httpresponse execute (httpurirequest request, httpcontext context) |
An httpresponse object is returned when the httpurirequest object and httpcontext object are executed. |
Httpresponse Interface
The httpresponse interface defines a series of set and get methods.
Method Name |
Description |
Public abstract httpentity getentity () |
Get an httpentity object |
Public abstract statusline getstatusline () |
Get a statusline (that is, the status line in the HTTP protocol. We know that the htpp status line consists of three parts: the HTTP protocol version, the response status code sent back by the server, and the text description of the status code) interface instance object |
Public abstract locale getlocale () |
Obtain the locale object. |
.... Corresponding Set Method |
|
Statusline Interface
Common statusline interface methods. You can also view it in the basicstatusline class of its implementation subclass.
Method Name |
Description |
Public abstract protocolversion getprotocolversion () |
Get a protolversion object. It is an HTTP encapsulation class. This class defines a series of methods. We can get the protocol name through its getprotocol method. getminor gets the htpp Protocol version. |
Public abstract string getreasonphrase () |
Text description of Status Code |
Public abstract int getstatuscode () |
Get response status code |
Httpentity Interface
Httpentity is an interface
Method Name |
Description |
Public abstract inputstream getcontent () |
To get an input stream object, we can use this stream to operate the file (for example, saving the file to the SD card) |
Public abstract header getcontenttype () |
Obtain the Content-Type header. |
Public abstract header getcontentencoding () |
Obtain the content-encoding header. |
We can use the entityutils class, which is a final class and a help class dedicated to handling httpentity.
Common Methods
Entityutils class
Common Methods of entityutils class
Method Name |
Description |
Public static string getcontentcharset (httpentity entity) |
Set the contentcharset of the httpentity object |
Public static byte [] tobytearray (httpentity entity) |
Convert httpclient into a byte array |
Public static string tostring (httpentity entity, string defaultcharset) |
Get the string content in httpentity using the specified encoding method |
Public static string tostring (httpentity entity) |
Get the string content in httpentity |
Namevaluepair
The namevaluepair interface is a simple closed key-value pair that provides only one getname () and one getvalue method. Implementation class basicnamevaulepair
Httpget class
Httpget implements the httprequest and httpurirequest interfaces.
Constructor
Method Name |
Description |
Public httpget () |
The non-parameter constructor is used to instantiate an object. |
Public httpget (URI) |
Construct an httpget object using a URI object |
Public httpget (string URI) |
Construct an httpget object by specifying the URI string address |
Httppost class
It also implements a series of interfaces such as httprequest and httpurirequest.
Constructor
Method Name |
Description |
Public httppost () |
The non-parameter constructor is used to instantiate an object. |
Public httppost (URI) |
Construct an httppost object using a URI object |
Public httppost (string URI) |
Construct an httppost object by specifying the URI string address |
After understanding all the common APIs above, we can use Apache HTTP to access HTTP resources.
Three steps:
1. Create an httpget or httppost object and pass in the http get or httppost Object Construction Method to the requested URL object.
2. defaultclent is the implementation class through the httpclent interface. and we already know that both the httpget and httppost classes have implemented the httpurirequest interface. Therefore, we can pass in the httpget or httppost object created in step 1. To get the httpresponse object.
3. Get some returned information through httpresponse and then extract it.
Instance image:
Part of the source code on the post:
Layout file:
<? XML version = "1.0" encoding = "UTF-8"?> <Linearlayout xmlns: Android = "http://schemas.android.com/apk/res/android" Android: Orientation = "vertical" Android: layout_width = "fill_parent" Android: layout_height = "fill_parent"> <linearlayout Android: orientation = "horizontal" Android: layout_width = "fill_parent" Android: layout_height = "wrap_content"> <textview Android: layout_width = "wrap_content" Android: layout_height = "wrap_content" Android: TEXT = "url:"/> <Edittext Android: Id = "@ + ID/urltext" Android: layout_width = "fill_parent" Android: layout_height = "wrap_content" Android: text = "http: // 10.0.2.2: 8080/NETServer/queryservlet? Bookid = 2 "/> </linearlayout> <linearlayout Android: Orientation =" horizontal "Android: layout_width =" fill_parent "Android: layout_height =" wrap_content "Android: gravity = "right"> <button Android: Id = "@ + ID/getbtn" Android: text = "GET request" Android: layout_width = "wrap_content" Android: layout_height = "wrap_content"/> <button Android: Id = "@ + ID/postbtn" Android: text = "POST request" Android: layout_width = "wrap_content" Android: layout_height = "wrap_content"/> </linearlayout> <textview Android: Id = "@ + ID/resultview" Android: layout_width = "fill_parent" Android: layout_height = "wrap_content"/> <linearlayout Android: Orientation = "horizontal" Android: layout_width = "fill_parent" Android: layout_height = "wrap_content"> <textview Android: layout_width = "wrap_content" Android: layout_height = "wrap_content" Android: text = "image URL:"/> <edittext Android: Id = "@ + ID/imageurltext" Android: layout_width = "fill_parent" Android: layout_height = "wrap_content" Android: text = "http://hiphotos.baidu.com/censhenlu/pic/item/3982b502915ddf9c7a8947c3.jpg"/> </linearlayout> <button Android: Id = "@ + ID/imgbtn" Android: TEXT = "get image" Android: layout_width = "wrap_content" Android: layout_height = "wrap_content" Android: layout_gravity = "right"/> <imageview Android: id = "@ + ID/imgeview01" Android: layout_height = "wrap_content" Android: layout_width = "fill_parent"/> </linearlayout>
Java code:
Package com.jiahui.net; import Java. io. inputstream; import Org. apache. HTTP. httpentity; import Org. apache. HTTP. httpresponse; import Org. apache. HTTP. statusline; import Org. apache. HTTP. client. httpclient; import Org. apache. HTTP. client. methods. httpget; import Org. apache. HTTP. client. methods. httppost; import Org. apache. HTTP. impl. client. defaulthttpclient; import Org. apache. HTTP. util. entityutils; import android. app. activity; import android. graphics. bitmap; import android. graphics. bitmapfactory; import android. OS. bundle; import android. view. view; import android. view. view. onclicklistener; import android. widget. button; import android. widget. edittext; import android. widget. imagebutton; import android. widget. imageview; import android. widget. textview; import android. widget. toast; public class httpdemoactivity extends activity {private button getbtn, postbtn, imagebtn; private edittext urltext, imageurltext; private textview resutlview; private imageview; Public void oncreate (bundle detail) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); urltext = (edittext) findviewbyid (R. id. urltext); imageurltext = (edittext) findviewbyid (R. id. imageurltext); resutlview = (textview) findviewbyid (R. id. resultview); getbtn = (button) findviewbyid (R. id. getbtn); postbtn = (button) findviewbyid (R. id. postbtn); imagebtn = (button) findviewbyid (R. id. imgbtn); imageview = (imageview) findviewbyid (R. id. imgeview01); getbtn. setonclicklistener (New onclicklistener () {@ override public void onclick (view v) {system. out. println (urltext. gettext (). tostring (); resutlview. settext (Request ("get", urltext. gettext (). tostring () ;}}); postbtn. setonclicklistener (New onclicklistener () {public void onclick (view v) {system. out. println (urltext. gettext (). tostring (); resutlview. settext (Request ("Post", urltext. gettext (). tostring () ;}}); imagebtn. setonclicklistener (New onclicklistener () {public void onclick (view v) {getimage (imageurltext. gettext (). tostring () ;}});} private string request (string method, string URL) {httpresponse = NULL; stringbuffer result = new stringbuffer (); try {If (method. equals ("get") {// 1. create an httpget object httpget = new httpget (URL) through a URL; // 2. return an httpresponse object httpclient = new defaulthttpclient (); httpresponse = httpclient.exe cute (httpget) through the excultclient excute method execution; // 3. get related information // get httpentiy httpentity = httpresponse. getentity (); // get some data // get the returned data result by using entityutils and specifying the encoding method. append (entityutils. tostring (httpentity, "UTF-8"); // obtain the statusline interface object statusline = httpresponse. getstatusline (); // get the Protocol; result. append ("Protocol:" + statusline. getprotocolversion () + "\ r \ n"); int statuscode = statusline. getstatuscode (); result. append ("Status Code:" + statuscode + "\ r \ n");} else if (method. equals ("Post") {// 1. create httpget object httppost = new httppost (URL) through URL; // 2. return an httpresponse object httpclient = new defaulthttpclient (); httpresponse = httpclient.exe cute (httppost) through the excultclient excute method execution; // 3. get related information // get httpentiy httpentity = httpresponse. getentity (); // get some data // get the returned data result by using entityutils and specifying the encoding method. append (entityutils. tostring (httpentity, "UTF-8"); statusline = httpresponse. getstatusline (); statusline. getprotocolversion (); int statuscode = statusline. getstatuscode (); result. append ("Status Code:" + statuscode + "\ r \ n") ;}} catch (exception e) {toast. maketext (httpdemoactivity. this, "network connection exception", toast. length_long ). show ();} return result. tostring ();} public void getimage (string URL) {try {// 1. create an httpget object httpget = new httpget (URL) through a URL; // 2. an httpresponse object httpclient = new defaulthttpclient (); httpresponse = httpclient.exe cute (httpget); // 3. get related information // get httpentiy httpentity = httpresponse. getentity (); // 4. through httpentiy. getcontent gets an input stream inputstream = httpentity. getcontent (); system. out. println (inputstream. available (); // create a bitmap Bitmap bitmap = bitmapfactory through the imported stream. decodestream (inputstream); // sets imageview. setimagebitmap (Bitmap);} catch (exception e) {toast. maketext (httpdemoactivity. this, "network connection exception", toast. length_long ). show ();}}}
Development considerations:
1. to access a local machine, you cannot write localhost or 127.0.0.1 as 10.0.2.2. This is because the android simulator uses it as the localhost. That is to say, it uses localhost or 127.0.0.1 in the code to access the simulator itself! If you want to access your computer on the simulator, use the built-in Android IP address 10.0.2.2 and 10.0.2.2, which is the specific IP address set by the simulator and the alias of your computer, use 10.0.2.2 on the simulator to access your computer.
2. Remember to add the network access permission.
<Uses-Permission Android: Name = "android. Permission. Internet"/>
Source code download: http://download.csdn.net/detail/jiahui524/3690598