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. }
复制代码
posted @ 2013-07-10 09:33  wanqi  阅读(10554)  评论(0编辑  收藏  举报