In Android development, we often use the network connection function and the server data interaction, this Android SDK provides Apache httpclient to facilitate our use of a variety of HTTP services. You can think of httpclient as a browser, through its API we can easily send out Get,post request (of course its function is far more than these)
This only describes how to use HttpClient to initiate a GET or POST request
Get mode
Copy Code code as follows:
First put the parameters in the list and then URL-encode the parameters
list<basicnamevaluepair> params = new linkedlist<basicnamevaluepair> ();
Params.add (New Basicnamevaluepair ("param1", "China"));
Params.add (New Basicnamevaluepair ("param2", "value2"));
To encode a parameter
String param = Urlencodedutils.format (params, "UTF-8");
BaseURL
String BaseURL = "http://ubs.free4lab.com/php/method.php";
Stitching URLs and parameters
HttpGet GetMethod = new HttpGet (BaseURL + "?" + param);
HttpClient httpclient = new Defaulthttpclient ();
try {
HttpResponse response = Httpclient.execute (GetMethod); Initiating a GET request
LOG.I (TAG, "Rescode =" + Response.getstatusline (). Getstatuscode ()); Get Response code
LOG.I (TAG, "result =" + entityutils.tostring (response.getentity (), "Utf-8"))//Get Server response content
catch (Clientprotocolexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
Post method
Copy Code code as follows:
In the same way as get, put the argument first into the list
params = new linkedlist<basicnamevaluepair> ();
Params.add (New Basicnamevaluepair ("param1", "POST Method"));
Params.add (New Basicnamevaluepair ("Param2", "second parameter"));
try {
HttpPost Postmethod = new HttpPost (BaseURL);
Postmethod.setentity (New urlencodedformentity (params, "utf-8")); Fill in post entity with parameters
HttpResponse response = Httpclient.execute (Postmethod); Perform post methods
LOG.I (TAG, "Rescode =" + Response.getstatusline (). Getstatuscode ()); Get Response code
LOG.I (TAG, "result =" + entityutils.tostring (response.getentity (), "Utf-8")); Get response Content
catch (Unsupportedencodingexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
catch (Clientprotocolexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}