Android HttpClient GET或者POST請求基本使用方法

在Android開發中咱們常常會用到網絡鏈接功能與服務器進行數據的交互,爲此Android的SDK提供了Apache的HttpClient來方便咱們使用各類Http服務。你能夠把HttpClient想象成一個瀏覽器,經過它的API咱們能夠很方便的發出GET,POST請求(它的功能遠不止這些,這裏只介紹如何使用HttpClient發起GET或者POST請求)php


GET 方式瀏覽器


//先將參數放入List,再對參數進行URL編碼
List params = new LinkedList();
params.add(new BasicNameValuePair("param1", "中國"));
params.add(new BasicNameValuePair("param2", "value2"));
//對參數編碼
String param = URLEncodedUtils.format(params, "UTF-8");
//baseUrl
String baseUrl = "http://ubs.free4lab.com/php/method.php";
//將URL與參數拼接
HttpGet getMethod = new HttpGet(baseUrl + "?" + param);服務器


HttpClient httpClient = new DefaultHttpClient();
try {
HttpResponse response = httpClient.execute(getMethod); //發起GET請求
Log.i(TAG, "resCode = " + response.getStatusLine().getStatusCode()); //獲取響應碼
Log.i(TAG, "result = " + EntityUtils.toString(response.getEntity(), "utf-8"));//獲取服務器響應內容
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}網絡


POST方式post

 


//和GET方式同樣,先將參數放入List
params = new LinkedList();
params.add(new BasicNameValuePair("param1", "Post方法"));
params.add(new BasicNameValuePair("param2", "第二個參數"));編碼


try {
HttpPost postMethod = new HttpPost(baseUrl);
postMethod.setEntity(new UrlEncodedFormEntity(params, "utf-8")); //將參數填入POST Entity中code


HttpResponse response = httpClient.execute(postMethod); //執行POST方法
Log.i(TAG, "resCode = " + response.getStatusLine().getStatusCode()); //獲取響應碼
Log.i(TAG, "result = " + EntityUtils.toString(response.getEntity(), "utf-8")); //獲取響應內容orm


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

相關文章
相關標籤/搜索