In Android development, we often use the network connection function to interact with the server. Therefore, the Android SDK provides Apache HttpClient to facilitate the use of various Http Services. You can think of HttpClient as a browser. Through its API, we can easily send GET and POST requests (of course, its functions are far more than that)
This document only describes how to use HttpClient to initiate GET or POST requests.
GET MethodCopy codeThe Code is as follows: // first put the parameter into the List, and then encode the parameter URL
List <BasicNameValuePair> params = new parameter List <BasicNameValuePair> ();
Params. add (new BasicNameValuePair ("param1", "China "));
Params. add (new BasicNameValuePair ("param2", "value2 "));
// Encode Parameters
String param = URLEncodedUtils. format (params, "UTF-8 ");
// BaseUrl
String baseUrl = "http://ubs.free4lab.com/php/method.php ";
// Concatenate the URL and Parameters
HttpGet getMethod = new HttpGet (baseUrl + "? "+ Param );
HttpClient httpClient = new DefaultHttpClient ();
Try {
HttpResponse response = httpClient.exe cute (getMethod); // initiate a GET request
Log. I (TAG, "resCode =" + response. getStatusLine (). getStatusCode (); // get the 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 methodCopy codeThe Code is as follows: // The same as the GET method, first put the parameter into the List
Params = new parameter list <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"); // enter the parameter in POST Entity.
HttpResponse response = httpClient.exe cute (postMethod); // execute the POST method
Log. I (TAG, "resCode =" + response. getStatusLine (). getStatusCode (); // get the response code
Log. I (TAG, "result =" + EntityUtils. toString (response. getEntity (), "UTF-8"); // get the 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 ();
}