Android HttpClient GET or POST request basic usage methods

  • 2020-05-07 20:24:45
  • OfStack

In the development of Android, we often use the network connection function to interact with the server for data. For this reason, SDK of Android provides HttpClient of Apache to facilitate us to use various Http services. You can think of HttpClient as a browser, with API we can easily make GET, POST requests (of course it's much more than that)

This only shows how to use HttpClient to initiate GET or POST requests
GET way
 
// Put the parameters in first List , and then the parameters URL coding  
List<BasicNameValuePair> params = new LinkedList<BasicNameValuePair>(); 
params.add(new BasicNameValuePair("param1", " China ")); 
params.add(new BasicNameValuePair("param2", "value2")); 
// Parameter coding  
String param = URLEncodedUtils.format(params, "UTF-8"); 
//baseUrl 
String baseUrl = "http://ubs.free4lab.com/php/method.php"; 
// will URL And parameter splicing  
HttpGet getMethod = new HttpGet(baseUrl + "?" + param); 

HttpClient httpClient = new DefaultHttpClient(); 
try { 
HttpResponse response = httpClient.execute(getMethod); // initiate GET request  
Log.i(TAG, "resCode = " + response.getStatusLine().getStatusCode()); // Get response code  
Log.i(TAG, "result = " + EntityUtils.toString(response.getEntity(), "utf-8"));// Gets the server response content  
} catch (ClientProtocolException e) { 
// TODO Auto-generated catch block 
e.printStackTrace(); 
} catch (IOException e) { 
// TODO Auto-generated catch block 
e.printStackTrace(); 
} 

POST way
 
// and GET way 1 Sample, first put the parameters in List 
params = new LinkedList<BasicNameValuePair>(); 
params.add(new BasicNameValuePair("param1", "Post methods ")); 
params.add(new BasicNameValuePair("param2", " The first 2 A parameter ")); 

try { 
HttpPost postMethod = new HttpPost(baseUrl); 
postMethod.setEntity(new UrlEncodedFormEntity(params, "utf-8")); // Fill in the parameters POST Entity In the  

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(); 
} 

Related articles: