Android提交數據到服務器的兩種方式四種方法


本帖最后由 yanghe123 於 2012-6-7 09:58 編輯

Android應用開發中,會經常要提交數據到服務器和從服務器得到數據,本文主要是給出了利用http協議采用HttpClient方式向服務器提交數據的方法。
代碼比較簡單,這里不去過多的闡述,直接看代碼。
  1. /**
  2. * @author Dylan 本類封裝了Android中向web服務器提交數據的兩種方式四種方法
  3. */
  4. public class SubmitDataByHttpClientAndOrdinaryWay {
  5. **
  6.   * 使用get請求以普通方式提交數據
  7.   * 
  8.   * @param map
  9.   *            傳遞進來的數據,以map的形式進行了封裝
  10.   * @param path
  11.   *            要求服務器servlet的地址
  12.   * @return 返回的boolean類型的參數
  13.   * @throws Exception
  14.   */
  15. public Boolean submitDataByDoGet(Map<String, String> map, String path)
  16.    throws Exception {
  17.   // 拼湊出請求地址
  18.   StringBuilder sb = new StringBuilder(path);
  19.   sb.append("?");
  20.   for (Map.Entry<String, String> entry : map.entrySet()) {
  21.    sb.append(entry.getKey()).append("=").append(entry.getValue());
  22.    sb.append("&");
  23.   }
  24.   sb.deleteCharAt(sb.length() - 1);
  25.   String str = sb.toString();
  26.   System.out.println(str);
  27.   URL Url = new URL(str);
  28.   HttpURLConnection HttpConn = (HttpURLConnection) Url.openConnection();
  29.   HttpConn.setRequestMethod("GET");
  30.   HttpConn.setReadTimeout(5000);
  31.   // GET方式的請求不用設置什么DoOutPut()之類的嗎?
  32.   if (HttpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
  33.    return true;
  34.   }
  35.   return false;
  36. }
  37. /**
  38.   * 普通方式的DoPost請求提交數據
  39.   * 
  40.   * @param map
  41.   *            傳遞進來的數據,以map的形式進行了封裝
  42.   * @param path
  43.   *            要求服務器servlet的地址
  44.   * @return 返回的boolean類型的參數
  45.   * @throws Exception
  46.   */
  47. public Boolean submitDataByDoPost(Map<String, String> map, String path) throws Exception {
  48. // 注意Post地址中是不帶參數的,所以newURL的時候要注意不能加上后面的參數
  49.   URL Url = new URL(path);
  50.   // Post方式提交的時候參數和URL是分開提交的,參數形式是這樣子的:name=y&age=6
  51.   StringBuilder sb = new StringBuilder();
  52.   // sb.append("?");
  53.   for (Map.Entry<String, String> entry : map.entrySet()) {
  54.    sb.append(entry.getKey()).append("=").append(entry.getValue());
  55.    sb.append("&");
  56.   }
  57.   sb.deleteCharAt(sb.length() - 1);
  58.   String str = sb.toString();[/font][/size]
  59. HttpURLConnection HttpConn = (HttpURLConnection) Url.openConnection();
  60.   HttpConn.setRequestMethod("POST");
  61.   HttpConn.setReadTimeout(5000);
  62.   HttpConn.setDoOutput(true);
  63.   HttpConn.setRequestProperty("Content-Type",
  64.     "application/x-www-form-urlencoded");
  65.   HttpConn.setRequestProperty("Content-Length",
  66.     String.valueOf(str.getBytes().length));
  67.   OutputStream os = HttpConn.getOutputStream();
  68.   os.write(str.getBytes());
  69.   if (HttpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
  70.    return true;
  71.   }
  72.   return false;
  73. }
  74. /**
  75.   * 以HttpClient的DoGet方式向服務器發送請數據
  76.   * 
  77.   * @param map
  78.   *            傳遞進來的數據,以map的形式進行了封裝
  79.   * @param path
  80.   *            要求服務器servlet的地址
  81.   * @return 返回的boolean類型的參數
  82.   * @throws Exception
  83.   */
  84. public Boolean submitDataByHttpClientDoGet(Map<String, String> map,
  85.    String path) throws Exception {
  86.   HttpClient hc = new DefaultHttpClient();
  87.   // 請求路徑
  88.   StringBuilder sb = new StringBuilder(path);
  89.   sb.append("?");
  90.   for (Map.Entry<String, String> entry : map.entrySet()) {
  91.    sb.append(entry.getKey()).append("=").append(entry.getValue());
  92.    sb.append("&");
  93.   }
  94.   sb.deleteCharAt(sb.length() - 1);
  95.   String str = sb.toString();
  96.   System.out.println(str);
  97.   HttpGet request = new HttpGet(sb.toString());[/font][/size]
  98. HttpResponse response = hc.execute(request);
  99.   if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) {
  100.    return true;
  101.   }
  102.   return false;
  103. }
復制代碼
  1. /**
  2.   * 以HttpClient的DoPost方式提交數據到服務器
  3.   * 
  4.   * @param map
  5.   *            傳遞進來的數據,以map的形式進行了封裝
  6.   * @param path
  7.   *            要求服務器servlet的地址
  8.   * @return 返回的boolean類型的參數
  9.   * @throws Exception
  10.   */
  11. public Boolean submintDataByHttpClientDoPost(Map<String, String> map, String path) throws Exception {
  12.   
  13. // 1. 獲得一個相當於瀏覽器對象HttpClient,使用這個接口的實現類來創建對象,DefaultHttpClient
  14.   HttpClient hc = new DefaultHttpClient();
  15.   // DoPost方式請求的時候設置請求,關鍵是路徑
  16.   HttpPost request = new HttpPost(path);
  17.   // 2. 為請求設置請求參數,也即是將要上傳到web服務器上的參數
  18.   List<NameValuePair> parameters = new ArrayList<NameValuePair>();
  19.   for (Map.Entry<String, String> entry : map.entrySet()) {
  20.    NameValuePair nameValuePairs = new BasicNameValuePair(
  21.      entry.getKey(), entry.getValue());
  22.    parameters.add(nameValuePairs);
  23.   }
  24.   // 請求實體HttpEntity也是一個接口,我們用它的實現類UrlEncodedFormEntity來創建對象,注意后面一個String類型的參數是用來指定編碼的
  25.   HttpEntity entity = new UrlEncodedFormEntity(parameters, "UTF-8");
  26.   request.setEntity(entity);
  27.   // 3. 執行請求
  28.   HttpResponse response = hc.execute(request);
  29.   // 4. 通過返回碼來判斷請求成功與否
  30.   if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) {
  31.    return true;
  32.   }
  33.   return false;
  34. }
  35. }
復制代碼


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM