Android HttpClient基本使用方法
這裏隻介紹如何使用HttpClient發起GET或者POST請求
GET 方式
- //先將參數放入List,再對參數進行URL編碼
- List<BasicNameValuePair> params = new LinkedList<BasicNameValuePair>();
- params.add(new BasicNameValuePair("param1", "中國"));
- params.add(new BasicNameValuePair("param2", "value2"));
- //對參數編碼
- String param = URLEncodedUtils.format(params, "UTF-8");
- //baseUrl
- String baseUrl = "https://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方式
- //和GET方式一樣,先將參數放入List
- params = new LinkedList<BasicNameValuePair>();
- 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中
- HttpResponse response = httpClient.execute(postMethod); //執行POST方法
- Log.i(TAG, "resCode = " + response.getStatusLine().getStatusCode()); //獲取響應碼
- Log.i(TAG, "result = " + EntityUtils.toString(response.getEntity(), "utf-8")); //獲取響應內容
- } 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();
- }
最後更新:2017-04-03 22:31:03