服务电话:0531-81180830 | 24小时服务:13176691830
公司新闻

【安卓笔记】android客户端与服务端交互的三种方式 .

android客户端向服务器通信一般有以下选择:
1.传统的java.net.HttpURLConnection类
2.apache的httpClient框架(已纳入android.jar中,可直接使用)
3.github上的开源框架async-http(基于httpClient)
----------------------------------------------------------------------------------
下面分别记录这三种方式的使用,以后忘了就来看看~
下面开始贴代码大笑

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

上一篇:[Unity3d]小地图的制作 . 下一篇:腾讯微博Android客户端开发——OAuth认证介绍 .