Android网络通信的方式

来源:互联网 发布:知乎 张佳玮 旅行 编辑:程序博客网 时间:2024/05/21 09:40

如今,手机应用渗透到各行各业,数量难以计数,其中大多数应用都会使用到网络,与服务器的交互势不可挡,那么android当中访问网络有哪些方式呢?

现在总结了六种方式:

(1)针对TCP/IP的Socket、ServerSocket

(2)针对UDP的DatagramSocket、DatagramPackage。这里需要注意的是,考虑到Android设备通常是手持终端,IP都是随着上网进行分配的。不是固定的。因此开发也是有一点与普通互联网应用有所差异的。

(3)针对直接URL的HttpURLConnection。

(4)Google集成了Apache HTTP客户端,可使用HTTP进行网络编程。

(5)使用WebService。Android可以通过开源包如jackson去支持Xmlrpc和Jsonrpc,另外也可以用Ksoap2去实现Webservice。

(6)直接使用WebView视图组件显示网页。基于WebView 进行开发,Google已经提供了一个基于chrome-lite的Web浏览器,直接就可以进行上网浏览网页。

一、socket与serverSocket

客户端代码

[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. public class TestNetworkActivity extends Activity implements OnClickListener{  
  2.     private Button connectBtn;  
  3.     private Button sendBtn;  
  4.     private TextView showView;  
  5.     private EditText msgText;  
  6.     private Socket socket;  
  7.     private Handler handler;  
  8.     @Override  
  9.     protected void onCreate(Bundle savedInstanceState) {  
  10.           
  11.         super.onCreate(savedInstanceState);  
  12.   
  13.         setContentView(R.layout.test_network_main);  
  14.   
  15.         connectBtn = (Button) findViewById(R.id.test_network_main_btn_connect);  
  16.         sendBtn = (Button) findViewById(R.id.test_network_main_btn_send);  
  17.         showView = (TextView) findViewById(R.id.test_network_main_tv_show);  
  18.         msgText = (EditText) findViewById(R.id.test_network_main_et_msg);  
  19.         connectBtn.setOnClickListener(this);  
  20.         sendBtn.setOnClickListener(this);  
  21.           
  22.         handler = new Handler(){  
  23.             @Override  
  24.             public void handleMessage(Message msg) {  
  25.                 super.handleMessage(msg);  
  26.                 String data = msg.getData().getString("msg");  
  27.                 showView.setText("来自服务器的消息:"+data);  
  28.             }  
  29.         };  
  30.     }  
  31.     @Override  
  32.     public void onClick(View v) {  
  33.         //连接服务器  
  34.         if(v == connectBtn){  
  35.             connectServer();  
  36.         }  
  37.         //发送消息  
  38.         if(v == sendBtn){  
  39.             String msg = msgText.getText().toString();  
  40.             send(msg);  
  41.         }  
  42.     }  
  43.        /**   
  44.      *连接服务器的方法  
  45.      */  
  46.     public void connectServer(){  
  47.         try {  
  48.             socket = new Socket("192.168.1.100",4000);  
  49.             System.out.println("连接服务器成功");  
  50.             recevie();  
  51.         } catch (Exception e) {  
  52.             System.out.println("连接服务器失败"+e);  
  53.             e.printStackTrace();  
  54.         }   
  55.     }  
  56.        /**  
  57.      *发送消息的方法  
  58.      */  
  59.     public void send(String msg){  
  60.         try {  
  61.             PrintStream ps = new PrintStream(socket.getOutputStream());  
  62.             ps.println(msg);  
  63.             ps.flush();  
  64.         } catch (IOException e) {  
  65.               
  66.             e.printStackTrace();  
  67.         }  
  68.     }  
  69.        /**  
  70.      *读取服务器传回的方法  
  71.      */  
  72.     public void recevie(){  
  73.   
  74.         new Thread(){  
  75.             public void run(){  
  76.                 while(true){  
  77.                     try {  
  78.                         InputStream is = socket.getInputStream();  
  79.                         BufferedReader br = new BufferedReader(new InputStreamReader(is));  
  80.                         String str = br.readLine();  
  81.                         Message message = new Message();  
  82.                         Bundle bundle = new Bundle();  
  83.                         bundle.putString("msg", str);  
  84.                         message.setData(bundle);  
  85.                         handler.sendMessage(message);  
  86.                           
  87.                     } catch (IOException e) {  
  88.                           
  89.                         e.printStackTrace();  
  90.                     }  
  91.                 }  
  92.             }  
  93.         }.start();  
  94.       
  95.     }  
  96. }  

二、RUL、URLConnection、httpURLConnection、ApacheHttp、WebView

[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. public class TestURLActivity extends Activity implements OnClickListener {  
  2.     private Button connectBtn;  
  3.     private Button urlConnectionBtn;  
  4.     private Button httpUrlConnectionBtn;  
  5.     private Button httpClientBtn;  
  6.     private ImageView showImageView;  
  7.     private TextView showTextView;  
  8.     private WebView webView;  
  9.   
  10.     @Override  
  11.     protected void onCreate(Bundle savedInstanceState) {  
  12.           
  13.         super.onCreate(savedInstanceState);  
  14.         setContentView(R.layout.test_url_main);  
  15.   
  16.         connectBtn = (Button) findViewById(R.id.test_url_main_btn_connect);  
  17.         urlConnectionBtn = (Button) findViewById(R.id.test_url_main_btn_urlconnection);  
  18.         httpUrlConnectionBtn = (Button) findViewById(R.id.test_url_main_btn_httpurlconnection);  
  19.         httpClientBtn = (Button) findViewById(R.id.test_url_main_btn_httpclient);  
  20.         showImageView = (ImageView) findViewById(R.id.test_url_main_iv_show);  
  21.         showTextView = (TextView) findViewById(R.id.test_url_main_tv_show);  
  22.         webView = (WebView) findViewById(R.id.test_url_main_wv);  
  23.         connectBtn.setOnClickListener(this);  
  24.         urlConnectionBtn.setOnClickListener(this);  
  25.         httpUrlConnectionBtn.setOnClickListener(this);  
  26.         httpClientBtn.setOnClickListener(this);  
  27.     }  
  28.   
  29.     @Override  
  30.     public void onClick(View v) {  
  31.         // 直接使用URL对象进行连接  
  32.         if (v == connectBtn) {  
  33.               
  34.             try {  
  35.                 URL url = new URL("http://192.168.1.100:8080/myweb/image.jpg");  
  36.                 InputStream is = url.openStream();  
  37.                 Bitmap bitmap = BitmapFactory.decodeStream(is);  
  38.                 showImageView.setImageBitmap(bitmap);  
  39.             } catch (Exception e) {  
  40.                   
  41.                 e.printStackTrace();  
  42.             }  
  43.   
  44.         }  
  45.         // 直接使用URLConnection对象进行连接     
  46.         if (v == urlConnectionBtn) {  
  47.             try {  
  48.                   
  49.                 URL url = new URL("http://192.168.1.100:8080/myweb/hello.jsp");  
  50.                 URLConnection connection = url.openConnection();  
  51.                 InputStream is = connection.getInputStream();  
  52.                 byte[] bs = new byte[1024];  
  53.                 int len = 0;  
  54.                 StringBuffer sb = new StringBuffer();  
  55.                 while ((len = is.read(bs)) != -1) {  
  56.                     String str = new String(bs, 0, len);  
  57.                     sb.append(str);  
  58.                 }  
  59.                 showTextView.setText(sb.toString());  
  60.             } catch (Exception e) {  
  61.                   
  62.                 e.printStackTrace();  
  63.             }  
  64.   
  65.         }  
  66.         // 直接使用HttpURLConnection对象进行连接  
  67.         if (v == httpUrlConnectionBtn) {  
  68.               
  69.             try {  
  70.                 URL url = new URL(  
  71.                         "http://192.168.1.100:8080/myweb/hello.jsp?username=abc");  
  72.                 HttpURLConnection connection = (HttpURLConnection) url  
  73.                         .openConnection();  
  74.                 connection.setRequestMethod("GET");  
  75.                 if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {  
  76.                     String message = connection.getResponseMessage();  
  77.                     showTextView.setText(message);  
  78.                 }  
  79.             } catch (Exception e) {  
  80.                   
  81.                 e.printStackTrace();  
  82.             }  
  83.         }  
  84.         // 使用ApacheHttp客户端进行连接(重要方法)  
  85.         if (v == httpClientBtn) {  
  86.             try {  
  87.                   
  88.                 HttpClient client = new DefaultHttpClient();  
  89.                 // 如果是Get提交则创建HttpGet对象,否则创建HttpPost对象  
  90.                 // HttpGet httpGet = new  
  91.                 // HttpGet("http://192.168.1.100:8080/myweb/hello.jsp?username=abc&pwd=321");  
  92.                 // post提交的方式  
  93.                 HttpPost httpPost = new HttpPost(  
  94.                         "http://192.168.1.100:8080/myweb/hello.jsp");  
  95.                 // 如果是Post提交可以将参数封装到集合中传递  
  96.                 List dataList = new ArrayList();  
  97.                 dataList.add(new BasicNameValuePair("username", "aaaaa"));  
  98.                 dataList.add(new BasicNameValuePair("pwd", "123"));  
  99.                 // UrlEncodedFormEntity用于将集合转换为Entity对象  
  100.                 httpPost.setEntity(new UrlEncodedFormEntity(dataList));  
  101.                 // 获取相应消息  
  102.                 HttpResponse httpResponse = client.execute(httpPost);  
  103.                 // 获取消息内容  
  104.                 HttpEntity entity = httpResponse.getEntity();  
  105.                 // 把消息对象直接转换为字符串  
  106.                 String content = EntityUtils.toString(entity);  
  107.                                 //showTextView.setText(content);  
  108.                   
  109.                 //通过webview来解析网页  
  110.                 webView.loadDataWithBaseURL(null, content, "text/html", "utf-8", null);  
  111.                 //给点url来进行解析  
  112.                 //webView.loadUrl(url);  
  113.             } catch (ClientProtocolException e) {  
  114.                    
  115.                 e.printStackTrace();  
  116.             } catch (IOException e) {  
  117.                    
  118.                 e.printStackTrace();  
  119.             }  
  120.         }  
  121.     }  
  122.   
  123. }  

三、使用webService

[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. public class LoginActivity extends Activity implements OnClickListener{  
  2.     private Button loginBtn;  
  3.     private static final String SERVICE_URL = "http://192.168.1.100:8080/loginservice/LoginServicePort";  
  4.     private static final String NAMESPACE = "http://service.lovo.com/";  
  5.     @Override  
  6.     protected void onCreate(Bundle savedInstanceState) {  
  7.            
  8.         super.onCreate(savedInstanceState);  
  9.         setContentView(R.layout.login_main);  
  10.         loginBtn = (Button) findViewById(R.id.login_main_btn_login);  
  11.         loginBtn.setOnClickListener(this);  
  12.     }  
  13.     @Override  
  14.     public void onClick(View v) {  
  15.           
  16.         if(v == loginBtn){  
  17.             //创建WebService的连接对象  
  18.             HttpTransportSE httpSE = new HttpTransportSE(SERVICE_URL);  
  19.             //通过SOAP1.1协议对象得到envelop  
  20.             SoapSerializationEnvelope envelop = new SoapSerializationEnvelope(SoapEnvelope.VER11);  
  21.             //根据命名空间和方法名来创建SOAP对象  
  22.             SoapObject soapObject = new SoapObject(NAMESPACE, "validate");  
  23.             //向调用方法传递参数  
  24.             soapObject.addProperty("arg0", "abc");  
  25.             soapObject.addProperty("arg1","123");  
  26.             //将SoapObject对象设置为SoapSerializationEnvelope对象的传出SOAP消息  
  27.             envelop.bodyOut = soapObject;  
  28.             try {  
  29.                 //开始调用远程的方法  
  30.                 httpSE.call(null, envelop);  
  31.                 //得到远程方法返回的SOAP对象  
  32.                 SoapObject resultObj = (SoapObject) envelop.bodyIn;  
  33.                 //根据名为return的键来获取里面的值,这个值就是方法的返回值  
  34.                 String returnStr = resultObj.getProperty("return").toString();  
  35.                 Toast.makeText(this, "返回值:"+returnStr, Toast.LENGTH_LONG).show();  
  36.             } catch (IOException e) {  
  37.                    
  38.                 e.printStackTrace();  
  39.             } catch (XmlPullParserException e) {  
  40.                    
  41.                 e.printStackTrace();  
  42.             }  
  43.               
  44.         }  
  45.               
  46.     }  
  47. }  
0 0
原创粉丝点击