在Android開發(fā)中,我們經(jīng)常使用網(wǎng)絡(luò)連接功能與服務(wù)器交互,因此android sdk提供了Apache的HTTP客戶端,以方便我們使用各種HTTP服務(wù),下面就讓武林技術(shù)頻道小編和大家分享Android HttpClient GET或者POST請(qǐng)求基本使用方法。
Android HttpClient GET或者POST請(qǐng)求基本使用方法
這里只介紹如何使用HttpClient發(fā)起GET或者POST請(qǐng)求
GET 方式
復(fù)制代碼 代碼如下:
//先將參數(shù)放入List,再對(duì)參數(shù)進(jìn)行URL編碼
List params = new LinkedList();
params.add(new BasicNameValuePair("param1", "中國"));
params.add(new BasicNameValuePair("param2", "value2"));
//對(duì)參數(shù)編碼
String param = URLEncodedUtils.format(params, "UTF-8");
//baseUrl
String baseUrl = "http://ubs.free4lab.com/php/method.php";
//將URL與參數(shù)拼接
HttpGet getMethod = new HttpGet(baseUrl + "?" + param);
HttpClient httpClient = new DefaultHttpClient();
try {
HttpResponse response = httpClient.execute(getMethod); //發(fā)起GET請(qǐng)求
Log.i(TAG, "resCode = " + response.getStatusLine().getStatusCode()); //獲取響應(yīng)碼
Log.i(TAG, "result = " + EntityUtils.toString(response.getEntity(), "utf-8"));//獲取服務(wù)器響應(yīng)內(nèi)容
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
POST方式
?
復(fù)制代碼 代碼如下:
?
//和GET方式一樣,先將參數(shù)放入List
params = new LinkedList();
params.add(new BasicNameValuePair("param1", "Post方法"));
params.add(new BasicNameValuePair("param2", "第二個(gè)參數(shù)"));
try {
HttpPost postMethod = new HttpPost(baseUrl);
postMethod.setEntity(new UrlEncodedFormEntity(params, "utf-8")); //將參數(shù)填入POST Entity中
HttpResponse response = httpClient.execute(postMethod); //執(zhí)行POST方法
Log.i(TAG, "resCode = " + response.getStatusLine().getStatusCode()); //獲取響應(yīng)碼
Log.i(TAG, "result = " + EntityUtils.toString(response.getEntity(), "utf-8")); //獲取響應(yīng)內(nèi)容
} 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();
}
通過武林技術(shù)頻道小編介紹的Android HttpClient GET或者POST請(qǐng)求基本使用方法,相信大家都有了一定的了解,如需了解更多的相關(guān)資訊,請(qǐng)繼續(xù)關(guān)注武林技術(shù)頻道吧!