首页 >  程序开发 >  移动开发 >  Android > 正文
android客户端与服务端交互的三种方式
2014-02-13       0  个评论    来源:【安卓笔记】android客户端与服务端交互的三种方式  
收藏     我要投稿
android客户端向服务器通信一般有以下选择: 1.传统的java.net.HttpURLConnection类 2.apache的httpClient框架(已纳入android.jar中,可直接使用) 3.github上的开源框架async-http(基于httpClient) ---------------------------------------------------------------------------------- 下面分别记录这三种方式的使用,
传统方式:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 /**       * 以get方式向服务端发送请求,并将服务端的响应结果以字符串方式返回。如果没有响应内容则返回空字符串       *       * @param url 请求的url地址       * @param params 请求参数       * @param charset url编码采用的码表       * @return       */      public static String getDataByGet(String url,Map params,String charset)      {          if (url == null )          {              return ;          }          url = url.trim();          URL targetUrl = null ;          try          {              if (params == null )              {                  targetUrl = new URL(url);              }              else              {                  StringBuilder sb = new StringBuilder(url+?);                  for (Map.Entry me : params.entrySet())                  { //                    解决请求参数中含有中文导致乱码问题                      sb.append(me.getKey()).append(=).append(URLEncoder.encode(me.getValue(),charset)).append(&);                  }                  sb.deleteCharAt(sb.length()- 1 );                  targetUrl = new URL(sb.toString());              }              Log.i(TAG,get:url----->+targetUrl.toString()); //打印log              HttpURLConnection conn = (HttpURLConnection) targetUrl.openConnection();              conn.setConnectTimeout( 3000 );              conn.setRequestMethod(GET);              conn.setDoInput( true );              int responseCode = conn.getResponseCode();              if (responseCode == HttpURLConnection.HTTP_OK)              {                  return stream2String(conn.getInputStream(),charset);              }          } catch (Exception e)          {              Log.i(TAG,e.getMessage());          }          return ; /**       *  以post方式向服务端发送请求,并将服务端的响应结果以字符串方式返回。如果没有响应内容则返回空字符串       * @param url 请求的url地址       * @param params 请求参数       * @param charset url编码采用的码表       * @return       */      public static String getDataByPost(String url,Map params,String charset)      {          if (url == null )          {              return ;          }          url = url.trim();          URL targetUrl = null ;          OutputStream out = null ;          try          {              targetUrl = new URL(url);              HttpURLConnection conn = (HttpURLConnection) targetUrl.openConnection();              conn.setConnectTimeout( 3000 );              conn.setRequestMethod(POST);              conn.setDoInput( true );              conn.setDoOutput( true );                            StringBuilder sb = new StringBuilder();              if (params!= null && !params.isEmpty())              {                  for (Map.Entry me : params.entrySet())                  { //                    对请求数据中的中文进行编码                      sb.append(me.getKey()).append(=).append(URLEncoder.encode(me.getValue(),charset)).append(&);                  }                  sb.deleteCharAt(sb.length()- 1 );              }              byte [] data = sb.toString().getBytes();              conn.setRequestProperty(Content-Type,application/x-www-form-urlencoded);              conn.setRequestProperty(Content-Length, String.valueOf(data.length));              out = conn.getOutputStream();              out.write(data);                            Log.i(TAG,post:url----->+targetUrl.toString()); //打印log                            int responseCode = conn.getResponseCode();              if (responseCode == HttpURLConnection.HTTP_OK)              {                  return stream2String(conn.getInputStream(),charset);              }          } catch (Exception e)          {              Log.i(TAG,e.getMessage());          }          return ;      } /**       * 将输入流对象中的数据输出到字符串中返回       * @param in       * @return       * @throws IOException       */      private static String stream2String(InputStream in,String charset) throws IOException      {          if (in == null )              return ;          byte [] buffer = new byte [ 1024 ];          ByteArrayOutputStream bout = new ByteArrayOutputStream();          int len = 0 ;          while ((len = in.read(buffer)) !=- 1 )          {              bout.write(buffer, 0 , len);          }          String result = new String(bout.toByteArray(),charset);          in.close();          return result;      }
使用httpClient: ?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 package cn.edu.chd.httpclientdemo.http; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.StatusLine; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import android.util.Log; /**   * @author Rowand jj   *   *http工具类,发送get/post请求   */ public final class HttpUtils {      private static final String TAG = HttpUtils;      private static final String CHARSET = utf- 8 ;      private HttpUtils(){}      /**       * 以get方式向指定url发送请求,将响应结果以字符串方式返回       * @param uri       * @return 如果没有响应数据返回null       */      public static String requestByGet(String url,Map data)      {          if (url == null )              return null ; //        构建默认http客户端对象          HttpClient client = new DefaultHttpClient();          try          { //            拼装url,并对中文进行编码              StringBuilder sb = new StringBuilder(url+?);              if (data != null )              {                  for (Map.Entry me : data.entrySet())                  {                      sb.append(URLEncoder.encode(me.getKey(),CHARSET)).append(=).append(URLEncoder.encode(me.getValue(),utf- 8 )).append(&);                  }                  sb.deleteCharAt(sb.length()- 1 );              }              Log.i(TAG, [get]--->uri:+sb.toString()); //            创建一个get请求              HttpGet get = new HttpGet(sb.toString()); //            执行get请求,获取http响应              HttpResponse response = client.execute(get); //            获取响应状态行              StatusLine statusLine = response.getStatusLine();              //请求成功              if (statusLine != null && statusLine.getStatusCode() == 200 )              { //                获取响应实体                  HttpEntity entity = response.getEntity();                  if (entity != null )                  {                      return readInputStream(entity.getContent());                  }              }          } catch (Exception e)          {              e.printStackTrace();          }          return null ;      }      /**       * 以post方式向指定url发送请求,将响应结果以字符串方式返回       * @param url       * @param data 以键值对形式表示的信息       * @return       */      public static String requestByPost(String url,Map data)      {          if (url == null )              return null ;          HttpClient client = new DefaultHttpClient();          HttpPost post = new HttpPost(url);          List params = null ;          try          {              Log.i(TAG, [post]--->uri:+url);              params = new ArrayList();              if (data != null )              {                  for (Map.Entry me : data.entrySet())                  {                      params.add( new BasicNameValuePair(me.getKey(),me.getValue()));                  }              } //            设置请求实体              post.setEntity( new UrlEncodedFormEntity(params,CHARSET)); //            获取响应信息              HttpResponse response = client.execute(post);              StatusLine statusLine = response.getStatusLine();              if (statusLine!= null && statusLine.getStatusCode()== 200 )              {                  HttpEntity entity = response.getEntity();                  if (entity!= null )                  {                      return readInputStream(entity.getContent());                  }              }          } catch (Exception e)          {              e.printStackTrace();          }          return null ;      }            /**       * 将流中的数据写入字符串返回       * @param is       * @return       * @throws IOException       */      private static String readInputStream(InputStream is) throws IOException      {          if (is == null )              return null ;          ByteArrayOutputStream bout = new ByteArrayOutputStream();          int len = 0 ;          byte [] buf = new byte [ 1024 ];          while ((len = is.read(buf))!=- 1 )          {              bout.write(buf, 0 , len);          }          is.close();          return new String(bout.toByteArray());      }      /**       * 将流中的数据写入字符串返回,以指定的编码格式       * 【如果服务端返回的编码不是utf-8,可以使用此方法,将返回结果以指定编码格式写入字符串】       * @param is       * @return       * @throws IOException       */      private static String readInputStream(InputStream is,String charset) throws IOException      {          if (is == null )              return null ;          ByteArrayOutputStream bout = new ByteArrayOutputStream();          int len = 0 ;          byte [] buf = new byte [ 1024 ];          while ((len = is.read(buf))!=- 1 )          {              bout.write(buf, 0 , len);          }          is.close();          return new String(bout.toByteArray(),charset);      } }
3.使用async-http框架,这个如果使用的话需要导入框架的jar包或者把 源码拷到工程下: 这个框架的好处是每次请求会开辟子线程,不会抛networkonmainthread异常,另外处理器类继承了Handler类,所以可以在里面更改UI。 注:这里使用的是最新的1.4.4版。 · ?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 /**       * 使用异步http框架发送get请求       * @param path get路径,中文参数需要编码(URLEncoder.encode)       */      public void doGet(String path)      {          AsyncHttpClient httpClient = new AsyncHttpClient();          httpClient.get(path, new AsyncHttpResponseHandler(){              @Override              public void onSuccess( int statusCode, Header[] headers, byte [] responseBody)              {                  if (statusCode == 200 )                  {                      try                      { //                        此处应该根据服务端的编码格式进行编码,否则会乱码                          tv_show.setText( new String(responseBody,utf- 8 ));                      } catch (UnsupportedEncodingException e)                      {                          e.printStackTrace();                      }                  }              }          });      }      /**       * 使用异步http框架发送get请求       * @param path       */      public void doPost(String path)      {          AsyncHttpClient httpClient = new AsyncHttpClient();          RequestParams params = new RequestParams();          params.put(paper,中文); //value可以是流、文件、对象等其他类型,很强大!!          httpClient.post(path, params, new AsyncHttpResponseHandler(){              @Override              public void onSuccess( int statusCode, Header[] headers, byte [] responseBody)              {                  if (statusCode == 200 )                  {                      tv_show.setText(

更多相关文章

  1. Android 实现TextView中 文字链接的方式
  2. Android 实现TextView中文字链接的方式
  3. [转]Android 实现TextView中文字链接的方式
  4. Android自己主动化測试解决方式
  5. android自制的软件如何添加到打开方式
  6. Android的四种启动方式
  7. Android中的几种网络请求方式详解 .
  8. Android中的IPC方式(二)

随机推荐

  1. Android:时间控件
  2. android各个文件分析
  3. 创建Android SD卡遇到的问题
  4. CyanogenMod | Android Community Rom ba
  5. Android开发中ConnectivityManager应用
  6. android最新源码下载
  7. ListView详解
  8. 使用Android自带Ant构建Apk
  9. Android基础之基本控件
  10. GoogleMap