10.2.1
Use
HttpURLConnection
1, first need to get to the httpurlconnection instance, generally just new out a URL object, and passed in
Target's network address, and then call the OpenConnection () method .
2, We can set the method used by the HTTP request.
There are two main methods, GET and POST. Get indicates that you want to get data from the server, while the POST
Indicates that you want to submit data to the server.
3, then you can do some free customization, such as setting the connection timeout, the number of milliseconds to read timeout, and the service
The service wants to get some message first class.
4, then call the getInputStream () method to obtain the input stream returned by the server, the remaining task is
The input stream is read,
5.
Finally, you can call the disconnect () method to shut down the HTTP connection.
// Open thread to initiate network request new thread (new runnable () { @Override public void run () { httpurlconnection connection = null; try { url url = new url ("http://www.baidu.com"); connection = (httpurlconnection) Url.openconnection (); the first line of code--android 400 connection.setrequestmethod ("GET"); Connection.setconnecttimeout (8000); connection.setreadtimeout (8000); inputstream in = connection.getinputstream (); // the input stream to be fetched 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; // Store the results returned by the server in Message message.obj = response.tostring (); handler.sendmessage ( Message); } catch (exception e) { e.printstacktrace (); } finally { if (Connection != null) { connection.disconnect (); } } } } ). Start (); }
So what if you want to submit data to the server? In fact, it's not complicated, just the HTTP request
method to POST and write out the data to be submitted before fetching the input stream. Note that each piece of data has to be keyed
value pairs exist, and data is separated from the data by A & symbol, for example, we want to submit a username and a secret to the server
Code, you can write it like this:
Connection.setrequestmethod ("POST");D ataoutputstream out = new DataOutputStream (Connection.getoutputstream ()); O Ut.writebytes ("username=admin&password=123456");
10.2.2 use HttpClient
1,httpcli ENT is an interface, so it is not possible to create an instance of it, usually creating a
build an instance of Defaulthttpclient as follows:
httpclient HttpClient = new Defaulthttpclient ();
2, next if you want to initiate a GET request, you can create a HttpGet object and pass in the target's network
address, and then call the Execute () method of HttpClient to
HttpGet httpget = new HttpGet ("http://www.baidu.com");
Httpclient.execute (HttpGet);
If initiating a POST request is a bit more complicated than GET, we need to create a HttpPost object,
and pass in the destination's 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 to a
Urlencodedformentity, and then call HttpPost's Setentity () method to build a good urlencodedformentity
Passed in as follows:
Li st<namevaluepair> params = new arraylist<namevaluepair> ();
params.add (New Basicnamevaluepair ("username", "admin"));
params.add (New Basicnamevaluepair ("Password", "123456"));
urlencodedformentity entity = new Urlencodedformentity (params, "utf-8");
httppost.setentity (entity);
< Span style= "Color:rgb (0, 0, 0); Font-family:courier New; font-size:9pt; Font-style:normal; Font-variant:normal; " >3, httpclient.execute (HttpPost);
< Span style= "Color:rgb (0, 0, 0); Font-family:courier New; font-size:9pt; Font-style:normal; Font-variant:normal; " >if (Httpresponse.getstatusline (). Getstatuscode () = = 200) {
// Both the request and the response were successful.
}
4,
next in this If the internal FETCH service returns the specific content, you can call the GetEntity () method to get to the
a httpentity instance, and then use the static method of entityutils.tostring () to convert the httpentity to a string
can be as follows:
httpentity entity = httpresponse.getentity ();
string response = entityutils.tostring (entity);
public class mainactivity extends activity implements onclicklistener {......@ Overridepublic void onclick (view v) {if (V.getid () == r.id.send_request) {sendrequestwithhttpclient ();}} Private void sendrequestwithhttpclient () {new thread (new runnable () {@ Overridepublic void run () {try {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 (); The first line of code--android404string response = entityutils.tostring (entity, "Utf-8" ); Message message = new message ();message.what = show_response;// Store the results returned by the server in message MESSAGE.OBJ&NBSP;=&NBSp;response.tostring (); handler.sendmessage (message);}} catch (exception e) {e.printstacktrace ();}}). Start ();} ......}
Android uses the HTTP protocol to access the network