Android之用HTTP的get,post,HttpClient三种方式向service提交文本数据

来源:互联网 发布:淘宝首页添加链接代码 编辑:程序博客网 时间:2024/04/30 01:56

客户端代码示例:

[java] view plaincopyprint?
  1. /**
  2. * HTTP请求
  3. * @author kesenhoo
  4. *
  5. */
  6. public class HttpRequest{
  7.     public staticboolean sendXML(String path, String xml)throws Exception{
  8.         byte[] data = xml.getBytes();
  9.         URL url = new URL(path);
  10.        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
  11.        conn.setRequestMethod("POST");
  12.        conn.setConnectTimeout(5 *1000);
  13.        //如果通过post提交数据,必须设置允许对外输出数据
  14.        conn.setDoOutput(true);
  15.        conn.setRequestProperty("Content-Type","text/xml; charset=UTF-8");
  16.        conn.setRequestProperty("Content-Length", String.valueOf(data.length));
  17.        OutputStream outStream = conn.getOutputStream();
  18.        outStream.write(data);
  19.        outStream.flush();
  20.        outStream.close();
  21.        if(conn.getResponseCode()==200) {
  22.               returntrue;
  23.         }
  24.          return false;
  25.    }
  26. /**
  27. * 通过get方式提交参数给服务器
  28. * @param path
  29. * @param params
  30. * @param enc
  31. * @return
  32. * @throws Exception
  33. */
  34. public staticboolean sendGetRequest(String path, Map<String, String> params, String enc)throws Exception {
  35.      //构造如下形式的字符串,这里的字符串依情况不同
  36.      // ?method=save&title=435435435&timelength=89&
  37.      //使用StringBuilder对象
  38.      StringBuilder sb = new StringBuilder(path);
  39.       sb.append('?');
  40.       //迭代Map
  41.       for(Map.Entry<String, String> entry : params.entrySet()){
  42.             sb.append(entry.getKey()).append('=')
  43.                  .append(URLEncoder.encode(entry.getValue(), enc)).append('&');
  44.        }
  45.        sb.deleteCharAt(sb.length()-1);
  46.        //打开链接
  47.        URL url = new URL(sb.toString());
  48.        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
  49.        conn.setRequestMethod("GET");
  50.        conn.setConnectTimeout(5 *1000);
  51.        //如果请求响应码是200,则表示成功
  52.        if(conn.getResponseCode()==200){
  53.             returntrue;
  54.         }
  55.            returnfalse;
  56.    }
  57. /**
  58. * 通过Post方式提交参数给服务器
  59. * @param path
  60. * @param params
  61. * @param enc
  62. * @return
  63. * @throws Exception
  64. */
  65. public staticboolean sendPostRequest(String path, Map<String, String> params, String enc)throws Exception {
  66.             //需要构造的字符串形式如下:
  67.             // title=dsfdsf&timelength=23&method=save
  68.            StringBuilder sb = new StringBuilder();
  69.            //如果参数不为空
  70.          if(params!=null && !params.isEmpty()){
  71.                for(Map.Entry<String, String> entry : params.entrySet()){
  72.                           //Post方式提交参数的话,不能省略内容类型与长度
  73.                           sb.append(entry.getKey()).append('=')
  74.                                 .append(URLEncoder.encode(entry.getValue(), enc)).append('&');
  75.                  }
  76.                 sb.deleteCharAt(sb.length()-1);
  77.             }
  78.              //得到实体的二进制数据
  79.              byte[] entitydata = sb.toString().getBytes();
  80.              URL url = new URL(path);
  81.              HttpURLConnection conn = (HttpURLConnection)url.openConnection();
  82.              conn.setRequestMethod("POST");
  83.              conn.setConnectTimeout(5 *1000);
  84.              //如果通过post提交数据,必须设置允许对外输出数据
  85.              conn.setDoOutput(true);
  86.               //这里只设置内容类型与内容长度的头字段
  87.               //内容类型Content-Type: application/x-www-form-urlencoded
  88.               //内容长度Content-Length: 38
  89.               conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
  90.               conn.setRequestProperty("Content-Length", String.valueOf(entitydata.length));
  91.               OutputStream outStream = conn.getOutputStream();
  92.               //把实体数据写入是输出流
  93.               outStream.write(entitydata);
  94.               //内存中的数据刷入
  95.               outStream.flush();
  96.               outStream.close();
  97.               //如果请求响应码是200,则表示成功
  98.               if(conn.getResponseCode()==200){
  99.                        returntrue;
  100.                }
  101.                        returnfalse;
  102.            }
  103. /**
  104. * 在遇上HTTPS安全模式或者操作cookie的时候使用HTTPclient会方便很多
  105. * 使用HTTPClient(开源项目)向服务器提交参数
  106. * @param path
  107. * @param params
  108. * @param enc
  109. * @return
  110. * @throws Exception
  111. */
  112. public staticboolean sendRequestFromHttpClient(String path, Map<String, String> params, String enc)throws Exception {
  113.           //需要把参数放到NameValuePair
  114.               List<NameValuePair> paramPairs = new ArrayList<NameValuePair>();
  115.               if(params!=null && !params.isEmpty()){
  116.                         for(Map.Entry<String, String> entry : params.entrySet()){
  117.                                     paramPairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
  118.                         }
  119.               }
  120.               //对请求参数进行编码,得到实体数据
  121.                UrlEncodedFormEntity entitydata = new UrlEncodedFormEntity(paramPairs, enc);
  122.                //构造一个请求路径
  123.                HttpPost post = new HttpPost(path);
  124.                //设置请求实体
  125.               post.setEntity(entitydata);
  126.                //浏览器对象
  127.                DefaultHttpClient client = new DefaultHttpClient();
  128.               //执行post请求
  129.               HttpResponse response = client.execute(post);
  130.               //从状态行中获取状态码,判断响应码是否符合要求
  131.                if(response.getStatusLine().getStatusCode()==200){
  132.                               returntrue;
  133.                }
  134.                        returnfalse;
  135.             }
  136. }

原创粉丝点击