SoFunction
Updated on 2025-03-01

Basic usage methods for Android HttpClient GET or POST requests

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

Here we only introduce how to use HttpClient to initiate GET or POST requests
GET method
Copy the codeThe code is as follows:

//Put the parameters into List first, and then URL encoding the parameters
List<BasicNameValuePair> params = new LinkedList<BasicNameValuePair>();
(new BasicNameValuePair("param1", "China"));
(new BasicNameValuePair("param2", "value2"));
//Encoding parameters
String param = (params, "UTF-8");
//baseUrl
String baseUrl = "http://ubs./php/";
//Style the URL with the parameters
HttpGet getMethod = new HttpGet(baseUrl + "?" + param);

HttpClient httpClient = new DefaultHttpClient();
try {
HttpResponse response = (getMethod); //Stack GET request
(TAG, "resCode = " + ().getStatusCode()); //Get the response code
(TAG, "result = " + ((), "utf-8"));//Get server response content
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
();
} catch (IOException e) {
// TODO Auto-generated catch block
();
}

POST method
Copy the codeThe code is as follows:

//Same as GET method, first put the parameters into List
params = new LinkedList<BasicNameValuePair>();
(new BasicNameValuePair("param1", "Post method"));
(new BasicNameValuePair("param2", "second parameter"));

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

HttpResponse response = (postMethod); //Execute POST method
(TAG, "resCode = " + ().getStatusCode()); //Get the response code
(TAG, "result = " + ((), "utf-8")); //Get response content

} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
();
} catch (IOException e) {
// TODO Auto-generated catch block
();
}