Android中网络通信的几种方式

来源:互联网 发布:hadoop sqlserver 编辑:程序博客网 时间:2024/06/05 22:48

Android网络编程分为两种:基于http协议的,和基于socket的。

基于Http协议:HttpClient、HttpURLConnection、AsyncHttpClient框架等
基于Socket:
(1)针对TCP/IP的Socket、ServerSocket
(2)针对UDP/IP的DatagramSocket、DatagramPackage
(3)Apache Mina框架

一、HttpURLConnection的实现方式
[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. String response = null;  
  2. Url url = new URL(path);  
  3. HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // 新建连接实例  
  4. connection.setConnectTimeout(20000);// 设置连接超时时间,单位毫秒  
  5. //connection.setReadTimeout(20000);// 设置读取数据超时时间,单位毫秒  
  6. connection.setDoInput(true);// 是否打开输入流 true|false  
  7. connection.setRequestMethod("POST");// 提交方法POST|GET  
  8. //connection.setUseCaches(false);// 是否缓存true|false  
  9. //connection.setRequestProperty("accept", "*/*");  
  10. //connection.setRequestProperty("Connection", "Keep-Alive");  
  11. //connection.setRequestProperty("Charset", "UTF-8");  
  12. //connection.setRequestProperty("Content-Length", String.valueOf(data.length));  
  13. //connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");  
  14. connection.connect();// 打开连接端口  
  15. int responseCode = conn.getResponseCode();  
  16. BufferedReader reader = null;  
  17. if (responseCode == 200) {  
  18.     reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));  
  19.     StringBuffer buffer = new StringBuffer();  
  20.     String line = "";  
  21.     while ((line = reader.readLine()) != null) {  
  22.         buffer.append(line);  
  23.     }  
  24.     response = buffer.toString();  
  25. else {  
  26.     response = "返回码:"+responseCode;  
  27. }  
  28. reader.close();  
  29. conn.disconnect();  
二、HttpClient实现方式
[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. HttpResponse mHttpResponse = null;  
  2. HttpEntity mHttpEntity = null;  
  3. //创建HttpPost对象  
  4. //HttpPost httppost = new HttpPost(path);  
  5. //设置httpPost请求参数  
  6. //httppost.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));  
  7. HttpGet httpGet = new HttpGet(path);     
  8. HttpClient httpClient = new DefaultHttpClient();  
  9. InputStream inputStream = null;  
  10. BufferedReader bufReader = null;  
  11. String result = "";  
  12. // 发送请求并获得响应对象  
  13. mHttpResponse = httpClient.execute(httpGet);//如果是“POST”方式就传httppost   
  14. if (mHttpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {  
  15.     // 获得响应的消息实体  
  16.     mHttpEntity = mHttpResponse.getEntity();  
  17.     // 获取一个输入流  
  18.     inputStream = mHttpEntity.getContent();  
  19.     bufReader = new BufferedReader(new InputStreamReader(inputStream));   
  20.     String line = "";  
  21.     while (null != (line = bufReader.readLine())) {  
  22.         result += line;  
  23.     }  
  24.     //result = EntityUtils.toString(mHttpResponse.getEntity());  
  25. }   
  26. if (inputStream != null) {  
  27.     inputStream.close();  
  28. }  
  29. bufReader.close();  
  30. if (httpClient != null) {  
  31.     httpClient.getConnectionManager().shutdown();  
  32. }  
三、实用AsyncHttpClient框架的实现方式:
[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. AsyncHttpClient client = new AsyncHttpClient();    
  2. client.get(url, new AsyncHttpResponseHandler() {    
  3.     @Override    
  4.     public void onSuccess(int i, Header[] headers, byte[] bytes) {                
  5.         String response = new String(bytes, 0, bytes.length, "UTF-8");                       
  6.     }    
  7.     @Override    
  8.     public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {    
  9.   
  10.     }    
  11. });   
四、使用WebView视图组件显示网页。
[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. myWebView.getSettings().setJavaScriptEnabled(true);    
  2. myWebView.setWebViewClient(new WebViewClient() {    
  3.     @Override    
  4.     public boolean shouldOverrideUrlLoading(WebView view, String url) {    
  5.         view.loadUrl(url);    
  6.         return true;    
  7.     }    
  8. });    
  9. myWebView.loadUrl("http://"+networkAddress);    

小提示:

对于HttpClient和HttpURLConnection我们该怎么选择呢?

在Android 2.2版本之前,由于HttpClient有较少的bug,因此我们选择它来使用。然而在Android 2.3版本及以后,HttpURLConnection则是最佳的选择。HttpUrlConnection对大部分工作进行了包装,屏蔽了不需要的细节,体积较小,因而非常适用于Android项目。并且HttpUrlConnection直接在系统层面做了缓存策略处理,可以加快重复请求的速度。由于其压缩(GZip)和缓存机制可以有效地减少网络访问的流量,在提升速度和省电方面也起到了较大的作用。对于新的应用程序应该更加偏向于使用HttpURLConnection,因为在后续Google官方会将更多的时间放在优化HttpURLConnection上面。


本文转载地址:http://blog.csdn.net/wdong_love_cl/article/details/51570961

0 0
原创粉丝点击