android学习日记14--网络通信

一、Android网络通信

  android网络通信一般有三种:java.net.*(标准Java接口)、org.apache接口(基于http协议)和android.net.*(Android网络接口),涉及到包括流、数据包套接字(socket)、Internet协议、常见Http处理等。android 内置HttpClient,简化和网站间的交互。但是不支持Web Services,需要利用ksoap2_android才能支持。


1、使用Socket进行通信
  Socket通常也称作"套接字",用于描述IP地址和端口,是一个通信链的句柄。Android Socket开发和JAVA Socket开发类似
无非是创建一个Socket服务端和Socket客户端进行通信。
Socket服务端代码:

 1 try{
 2             // 新建服务器Socket
 3             ServerSocket ss = new ServerSocket(8888);
 4             System.out.println("Listening...");
 5             while(true){
 6                 // 监听是否有客户端连上
 7                 Socket socket = ss.accept();
 8                 System.out.println("Client Connected...");
 9                 DataOutputStream dout = new DataOutputStream(socket.getOutputStream());
10                 Date d = new Date();
11                 // 演示传送个 当前时间给客户端
12                 dout.writeUTF(d.toLocaleString());
13                 dout.close();
14                 socket.close();
15             }
16         }
17         catch(Exception e){
18             e.printStackTrace();
19         }
20     }
View Code

Socket客户端代码:

 1 public void connectToServer(){                    //方法:连接客户端
 2             try{
 3                 Socket socket = new Socket("10.0.2.2", 8888);//创建Socket对象
 4                 DataInputStream din = new DataInputStream(socket.getInputStream());    //获得DataInputStream对象
 5                 String msg = din.readUTF();                             //读取服务端发来的消息
 6                 EditText et = (EditText)findViewById(R.id.et);        //获得EditText对象
 7                 if (null != msg) {
 8                     et.setText(msg);                                    //设置EditText对象
 9                 }else {
10                     et.setText("error data");
11                 }
12                 
13                 
14             }
15             catch(Exception e){                                        //捕获并打印异常
16                 e.printStackTrace();
17             }
18         }
View Code

  服务端是普通JAVA项目,先启动服务端,再启动客户端Android项目,客户端连上服务端,把当前时间数据从服务端发往客户端显示出来

注意:服务器与客户端无法链接的可能原因有:
a、AndroidManifest没有加访问网络的权限:<uses-permission android:name="android.permission.INTERNET"></uses-permission>
b、IP地址要使用:10.0.2.2,不能用localhost
c、模拟器不能配置代理

2、使用Http进行通信
  使用HttpClient在Android客户端访问Web,有点html知识都知道,提交表单有两种方式
get和post,Android客户端访问Web也是这两种方式。在本机先建个web应用(方便演示)。
data.jsp的代码:

 1 <%@page language="java" import="java.util.*" pageEncoding="utf-8"%> 
 2 <html> 
 3 <head> 
 4 <title> 
 5 Http Test 
 6 </title> 
 7 </head> 
 8 <body> 
 9 <% 
10 String type = request.getParameter("parameter"); 
11 String result = new String(type.getBytes("iso-8859-1"),"utf-8"); 
12 out.println("<h1>" + result + "</h1>"); 
13 %> 
14 </body> 
15 </html>
View Code

启动tomcat,访问http://192.168.1.101:8080/test/data.jsp?parameter=发送的参数

 

注意:192.168.1.101是我本机的IP,要替换成自己的IP。

 按钮监听代码:

 1 //绑定按钮监听器  
 2         get.setOnClickListener(new OnClickListener() {  
 3             @Override  
 4             public void onClick(View v) {  
 5                 //注意:此处ip不能用127.0.0.1或localhost,Android模拟器已将它自己作为了localhost  
 6                 String uri = "http://192.168.1.101:8080/test/data.jsp?parameter=以Get方式发送请求";  
 7                 textView.setText(get(uri));  
 8             }  
 9         });  
10         //绑定按钮监听器  
11         post.setOnClickListener(new OnClickListener() {  
12             @Override  
13             public void onClick(View v) {  
14                 String uri = "http://192.168.1.101:8080/test/data.jsp";  
15                 textView.setText(post(uri));  
16             }  
17         });  
View Code

 get方式请求代码:

 1 /** 
 2      * 以get方式发送请求,访问web 
 3      * @param uri web地址 
 4      * @return 响应数据 
 5      */  
 6     private static String get(String uri){  
 7         BufferedReader reader = null;  
 8         StringBuffer sb = null;  
 9         String result = "";  
10         HttpClient client = new DefaultHttpClient();  
11         HttpGet request = new HttpGet(uri);  
12         try {  
13             //发送请求,得到响应  
14             HttpResponse response = client.execute(request);  
15               
16             //请求成功  
17             if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){  
18                 reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));  
19                 sb = new StringBuffer();  
20                 String line = "";  
21                 String NL = System.getProperty("line.separator");  
22                 while((line = reader.readLine()) != null){  
23                     sb.append(line);  
24                 }  
25             }  
26         } catch (ClientProtocolException e) {  
27             e.printStackTrace();  
28         } catch (IOException e) {  
29             e.printStackTrace();  
30         }  
31         finally{  
32             try {  
33                 if (null != reader){  
34                     reader.close();  
35                     reader = null;  
36                 }  
37             } catch (IOException e) {  
38                 e.printStackTrace();  
39             }  
40         }  
41         if (null != sb){  
42             result =  sb.toString();  
43         }  
44         return result;  
45     }
View Code

 post方式请求代码:

 1 /** 
 2      * 以post方式发送请求,访问web 
 3      * @param uri web地址 
 4      * @return 响应数据 
 5      */  
 6     private static String post(String uri){  
 7         BufferedReader reader = null;  
 8         StringBuffer sb = null;  
 9         String result = "";  
10         HttpClient client = new DefaultHttpClient();  
11         HttpPost request = new HttpPost(uri);  
12           
13         //保存要传递的参数  
14         List<NameValuePair> params = new ArrayList<NameValuePair>();  
15         //添加参数  
16         params.add(new BasicNameValuePair("parameter","以Post方式发送请求"));  
17           
18         try {  
19             //设置字符集  
20             HttpEntity entity = new UrlEncodedFormEntity(params,"utf-8");  
21             //请求对象  
22             request.setEntity(entity);  
23             //发送请求  
24             HttpResponse response = client.execute(request);  
25               
26             //请求成功  
27             if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){  
28                 System.out.println("post success");  
29                 reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));  
30                 sb = new StringBuffer();  
31                 String line = "";  
32                 String NL = System.getProperty("line.separator");  
33                 while((line = reader.readLine()) != null){  
34                     sb.append(line);  
35                 }  
36             }  
37         } catch (ClientProtocolException e) {  
38             e.printStackTrace();  
39         } catch (IOException e) {  
40             e.printStackTrace();  
41         }  
42         finally{  
43             try {  
44                 //关闭流  
45                 if (null != reader){  
46                     reader.close();  
47                     reader = null;  
48                 }  
49             } catch (IOException e) {  
50                 e.printStackTrace();  
51             }  
52         }  
53         if (null != sb){  
54             result =  sb.toString();  
55         }  
56         return result;  
57     } 
View Code

点击'get'按钮:

点击'post'按钮

3、获取http网络资源

  其实这里就是前面讲Android数据存储的最后一种:网络存储。将txt文件和png图片放在tomcat服务器上,模拟器通过http路径去获取资源显示出来。

获取路径为:

1     String stringURL = "http://192.168.1.101:8080/test/test.txt";
2     String bitmapURL = "http://192.168.1.101:8080/test/crab.png";
View Code

获取文本资源代码:

 1 //方法,根据指定URL字符串获取网络资源
 2     public void getStringURLResources(){
 3         try{
 4             URL myUrl = new URL(stringURL);
 5             URLConnection myConn = myUrl.openConnection();    //打开连接
 6             InputStream in = myConn.getInputStream();        //获取输入流
 7             BufferedInputStream bis = new BufferedInputStream(in);//获取BufferedInputStream对象
 8             ByteArrayBuffer baf = new ByteArrayBuffer(bis.available());
 9             int data = 0;
10             while((data = bis.read())!= -1){        //读取BufferedInputStream中数据
11                 baf.append((byte)data);                //将数据读取到ByteArrayBuffer中
12             }
13             String msg = EncodingUtils.getString(baf.toByteArray(), "GBK");    //转换为字符串,用UTF-8中文会乱码
14             EditText et = (EditText)findViewById(R.id.et);        //获得EditText对象
15             et.setText(msg);                        //设置EditText控件中的内容
16         }
17         catch(Exception e){
18             e.printStackTrace();
19         }    
20     }
View Code

获取图片资源代码:

 1 public void getBitmapURLResources(){
 2         try{
 3             URL myUrl = new URL(bitmapURL);    //创建URL对象
 4             URLConnection myConn = myUrl.openConnection();            //打开连接
 5             InputStream in = myConn.getInputStream();            //获得InputStream对象
 6             Bitmap bmp = BitmapFactory.decodeStream(in);        //创建Bitmap
 7             ImageView iv = (ImageView)findViewById(R.id.iv);    //获得ImageView对象
 8             iv.setImageBitmap(bmp);                    //设置ImageView显示的内容
 9         }
10         catch(Exception e){
11             e.printStackTrace();
12         }
13     }
View Code

 注意:String msg = EncodingUtils.getString(baf.toByteArray(), "GBK");//转换为字符串,用UTF-8中文会乱码

运行效果:

原文地址:https://www.cnblogs.com/aiguozhe/p/3601881.html