Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 系列(八):使用 HttpClient 連接伺服器

編輯:關於 Android 程式設計

HttpClient 簡介:httpclient 是 Apache 上的開源專案,相當於對瀏覽器的簡單包裝。

一、透過 HttpClient 發送 GET 請求

 public static String sendDataByHttpClientGet(String path, String username, String password) throws Exception {
     // 1. 創建一個瀏覽器的 HttpClient 物件
     HttpClient client = new DefaultHttpClient();
     // 2. 輸入一個 url,創建一個 url
     String urlstr = path + "?name=" + URLEncoder.encode(username)
             + "&password=" + URLEncoder.encode(password);
     // httpGet 物件表示向指定的 url 發送 get 請求
     HttpGet httpGet = new HttpGet(urlstr);
     // 3. 執行 get 請求,並返回響應的數據
     HttpResponse response = client.execute(httpGet);
     // response.getStatusLine() 方法獲取相應的狀態行,並取得狀態碼
     if (response.getStatusLine().getStatusCode() == 200) {
         // response.getEntity() 方法獲取響應數據的實體,取得響應內容
         InputStream is = response.getEntity().getContent();
         // 將流轉成文本
         byte[] result = StreamTools.getBytes(is);
         return new String(result);
 }
     return null;
 }

二、透過 HttpClient 發送 POST 請求

 public static String sendDataByHttpClientPost(String path, String username,
         String password) throws Exception {
     // 1. 創建一個瀏覽器
     HttpClient client = new DefaultHttpClient();
     // 2. 構建一個 post 的請求
     HttpPost post = new HttpPost(path);
     // 創建請求實體物件中的參數,即鍵值對的集合
     List parameters = new ArrayList();
     parameters.add(new BasicNameValuePair("name", username));
     parameters.add(new BasicNameValuePair("password", password));
     // 創建請求實體物件,並指定字符編碼形式
     UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters, "utf-8");
     // 設置 post 請求的實體方法
     post.setEntity(entity);
     // 3. 執行 post 請求
     HttpResponse response = client.execute(post);
     // 判斷響應碼
     if (response.getStatusLine().getStatusCode() == 200) {
         InputStream is = response.getEntity().getContent();
         byte[] result = StreamTools.getBytes(is);
         return new String(result);
 }
     return null;
 }
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved