[Android開發]Android之使用HTTP的get,post,HttpClient三種方式向服務器端提交文本數據

客戶端代碼示例:

  1. /** 
  2.  * HTTP請求 
  3.  * @author kesenhoo 
  4.  * 
  5.  */  
  6. public class HttpRequest   
  7. {     
  8.     public static boolean sendXML(String path, String xml)throws Exception  
  9.     {  
  10.         byte[] data = xml.getBytes();  
  11.         URL url = new URL(path);  
  12.         HttpURLConnection conn = (HttpURLConnection)url.openConnection();  
  13.         conn.setRequestMethod("POST");  
  14.         conn.setConnectTimeout(5 * 1000);  
  15.         //如果通過post提交數據,必須設置允許對外輸出數據  
  16.         conn.setDoOutput(true);  
  17.         conn.setRequestProperty("Content-Type""text/xml; charset=UTF-8");  
  18.         conn.setRequestProperty("Content-Length", String.valueOf(data.length));  
  19.         OutputStream outStream = conn.getOutputStream();  
  20.         outStream.write(data);  
  21.         outStream.flush();  
  22.         outStream.close();  
  23.         if(conn.getResponseCode()==200)  
  24.         {  
  25.             return true;  
  26.         }  
  27.         return false;  
  28.     }  
  29.     /** 
  30.      * 通過get方式提交參數給服務器 
  31.      * @param path 
  32.      * @param params 
  33.      * @param enc 
  34.      * @return 
  35.      * @throws Exception 
  36.      */  
  37.     public static boolean sendGetRequest(String path, Map<String, String> params, String enc) throws Exception  
  38.     {  
  39.         //構造如下形式的字符串,這裏的字符串依情況不同  
  40.         // ?method=save&title=435435435&timelength=89&        
  41.         //使用StringBuilder對象  
  42.         StringBuilder sb = new StringBuilder(path);  
  43.         sb.append('?');       
  44.         //迭代Map  
  45.         for(Map.Entry<String, String> entry : params.entrySet())  
  46.         {  
  47.             sb.append(entry.getKey()).append('=')  
  48.                 .append(URLEncoder.encode(entry.getValue(), enc)).append('&');  
  49.         }  
  50.         sb.deleteCharAt(sb.length()-1);  
  51.         //打開鏈接  
  52.         URL url = new URL(sb.toString());  
  53.         HttpURLConnection conn = (HttpURLConnection)url.openConnection();  
  54.         conn.setRequestMethod("GET");  
  55.         conn.setConnectTimeout(5 * 1000);  
  56.         //如果請求響應碼是200,則表示成功  
  57.         if(conn.getResponseCode()==200)  
  58.         {  
  59.             return true;  
  60.         }  
  61.         return false;  
  62.     }  
  63.       
  64.     /** 
  65.      * 通過Post方式提交參數給服務器 
  66.      * @param path 
  67.      * @param params 
  68.      * @param enc 
  69.      * @return 
  70.      * @throws Exception 
  71.      */  
  72.     public static boolean sendPostRequest(String path, Map<String, String> params, String enc) throws Exception  
  73.     {  
  74.         //需要構造的字符串形式如下:  
  75.         // title=dsfdsf&timelength=23&method=save  
  76.         StringBuilder sb = new StringBuilder();  
  77.         //如果參數不爲空  
  78.         if(params!=null && !params.isEmpty())  
  79.         {  
  80.             for(Map.Entry<String, String> entry : params.entrySet())  
  81.             {  
  82.                 //Post方式提交參數的話,不能省略內容類型與長度  
  83.                 sb.append(entry.getKey()).append('=')  
  84.                     .append(URLEncoder.encode(entry.getValue(), enc)).append('&');  
  85.             }  
  86.             sb.deleteCharAt(sb.length()-1);  
  87.         }  
  88.         //得到實體的二進制數據  
  89.         byte[] entitydata = sb.toString().getBytes();  
  90.         URL url = new URL(path);  
  91.         HttpURLConnection conn = (HttpURLConnection)url.openConnection();  
  92.         conn.setRequestMethod("POST");  
  93.         conn.setConnectTimeout(5 * 1000);  
  94.         //如果通過post提交數據,必須設置允許對外輸出數據  
  95.         conn.setDoOutput(true);  
  96.         //這裏只設置內容類型與內容長度的頭字段  
  97.         //內容類型Content-Type: application/x-www-form-urlencoded  
  98.         //內容長度Content-Length: 38  
  99.         conn.setRequestProperty("Content-Type""application/x-www-form-urlencoded");  
  100.         conn.setRequestProperty("Content-Length", String.valueOf(entitydata.length));  
  101.         OutputStream outStream = conn.getOutputStream();  
  102.         //把實體數據寫入是輸出流  
  103.         outStream.write(entitydata);  
  104.         //內存中的數據刷入  
  105.         outStream.flush();  
  106.         outStream.close();  
  107.         //如果請求響應碼是200,則表示成功  
  108.         if(conn.getResponseCode()==200)  
  109.         {  
  110.             return true;  
  111.         }  
  112.         return false;  
  113.     }  
  114.       
  115.     /** 
  116.      * 在遇上HTTPS安全模式或者操作cookie的時候使用HTTPclient會方便很多 
  117.      * 使用HTTPClient(開源項目)向服務器提交參數 
  118.      * @param path 
  119.      * @param params 
  120.      * @param enc 
  121.      * @return 
  122.      * @throws Exception 
  123.      */  
  124.     public static boolean sendRequestFromHttpClient(String path, Map<String, String> params, String enc) throws Exception  
  125.     {  
  126.         //需要把參數放到NameValuePair  
  127.         List<NameValuePair> paramPairs = new ArrayList<NameValuePair>();  
  128.         if(params!=null && !params.isEmpty())  
  129.         {  
  130.             for(Map.Entry<String, String> entry : params.entrySet())  
  131.             {  
  132.                 paramPairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));  
  133.             }  
  134.         }  
  135.         //對請求參數進行編碼,得到實體數據  
  136.         UrlEncodedFormEntity entitydata = new UrlEncodedFormEntity(paramPairs, enc);  
  137.         //構造一個請求路徑  
  138.         HttpPost post = new HttpPost(path);   
  139.         //設置請求實體  
  140.         post.setEntity(entitydata);  
  141.         //瀏覽器對象  
  142.         DefaultHttpClient client = new DefaultHttpClient();   
  143.         //執行post請求  
  144.         HttpResponse response = client.execute(post);  
  145.         //從狀態行中獲取狀態碼,判斷響應碼是否符合要求  
  146.         if(response.getStatusLine().getStatusCode()==200)  
  147.         {  
  148.             return true;  
  149.         }  
  150.         return false;  
  151.     }  
  152. }  
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章