[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. }  
 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值