HttpClient: is an interface
You first need to create an instance of Defaulthttpclient
HttpClient httpclient=new defaulthttpclient ();
To send a GET request:
First 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);
To send a POST request:
Create a HttpPost object that is passed to the destination's network address:
HttpPost httppost=new httppost ("http://www.baidu.com");
A Namevaluepair collection is held to hold the arguments to be submitted, the collection of parameters is passed into a urlencodedformentity, and then the Setentity () of HttpPost is called. method to pass the built-in urlencodedformentity into:
List<namevaluepair>params=newarraylist<namevaluepair> ();
Params.add (New Basicnamevaluepair ("username", "admin"));
Params.add (New Basicnamevaluepair ("Password", "123456"));
Urlencodedformentity entity=newurlencodedformentity (params, "utf-8");
Httppost.setentity (entity);
Call the Execute () method of httpclient and pass the HttpPost object in:
Httpclient.execute (HttpPost);
After executing the Execute () method, a HttpResponse object is returned, and all information returned by the server is protected in HttpResponse.
The status code returned by the server is first removed, and if equal to 200 indicates that the request and response were successful:
If (Httpresponse.getstatusline (). Getstatuscode () ==200) {
Both the request and the response were successful.
Httpentityentity=httpresponse.getentity ();//Call the GetEntity () method to get to a httpentity instance
Stringresponse=entityutils.tostring (Entity, "utf-8"), or//with entityutils.tostring () This static method converts httpentity to a string, Prevents the data returned by the server from being in Chinese, so it is possible to specify the character set as Utf-8 when converting.
}
The importance of the HTTP protocol I don't have to say much, httpclient. Compared to the traditional JDK urlconnection, it adds ease of use and flexibility (specific differences that we'll discuss later), and it's not only easy for clients to send HTTP requests, It also facilitates the developer to test the interface (based on the HTTP protocol), which improves the efficiency of the development and facilitates the robustness of the code. So mastering httpclient is a very important compulsory content, after mastering httpclient, I believe that the understanding of the HTTP protocol will be more thorough.
HttpClient use in detail