Android网络通信总结

来源:互联网 发布:tp路由器mac地址过滤 编辑:程序博客网 时间:2024/06/01 19:52

Android的网络编程分为2种:Socket网络通信Http网络通信

Http通信以xml或者json(JavaScript Object Notation)为载体,相互通信数据。json:一种简单的数据格式,比xml更轻巧。json 是JavaScript原生格式,这意味着在JavaScript中处理json数据不需要任何特殊的API或工具包。

Socket与Http不同的是两个的协议不同:Socket是面向TCP/UDP协议(位于传输层)的,Http是面向HTTP协议(位于应用层)的。

Android对于Http网络通信,提供了标准的Java接口--HttpURLConnection接口和Apache的接口--HttpClient接口。同时Http通信也分为Post方式和Get方式,两个相比较的话,post传送的数据量比较大,安全性也比较发高。

下面展示了Android SDK中的一些与网络有关的API包名:

包                 描述                             

Java.net提供与联网有关的类,包括流和数据包(datagram)socket、internet协议和常见HTTP处理。该包是一个多功能网络资源

。。。。。。

Socket通信两种方式

1、基于TCP协议

android端实现:

[java] view plaincopy
  1.     protected void connectServerWithTCPSocket() {  
  2.   
  3.         Socket socket;  
  4.         try {// 创建一个Socket对象,并指定服务端的IP及端口号  
  5.             socket = new Socket("192.168.1.32"1989);  
  6.             // 创建一个InputStream用户读取要发送的文件。  
  7.             InputStream inputStream = new FileInputStream("e://a.txt");  
  8.             // 获取Socket的OutputStream对象用于发送数据。  
  9.             OutputStream outputStream = socket.getOutputStream();  
  10.             // 创建一个byte类型的buffer字节数组,用于存放读取的本地文件  
  11.             byte buffer[] = new byte[4 * 1024];  
  12.             int temp = 0;  
  13.             // 循环读取文件  
  14.             while ((temp = inputStream.read(buffer)) != -1) {  
  15.                 // 把数据写入到OuputStream对象中  
  16.                 outputStream.write(buffer, 0, temp);  
  17.             }  
  18.             // 发送读取的数据到服务端  
  19.             outputStream.flush();  
  20.   
  21.             /** 或创建一个报文,使用BufferedWriter写入,看你的需求 **/  
  22. //          String socketData = "[2143213;21343fjks;213]";  
  23. //          BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(  
  24. //                  socket.getOutputStream()));  
  25. //          writer.write(socketData.replace("\n", " ") + "\n");  
  26. //          writer.flush();  
  27.             /************************************************/  
  28.         } catch (UnknownHostException e) {  
  29.             e.printStackTrace();  
  30.         } catch (IOException e) {  
  31.             e.printStackTrace();  
  32.         }  
  33.   
  34.     }  

服务器端简单实现:

[java] view plaincopy
  1. public void ServerReceviedByTcp() {  
  2.     // 声明一个ServerSocket对象  
  3.     ServerSocket serverSocket = null;  
  4.     try {  
  5.         // 创建一个ServerSocket对象,并让这个Socket在1989端口监听  
  6.         serverSocket = new ServerSocket(1989);  
  7.         // 调用ServerSocket的accept()方法,接受客户端所发送的请求,  
  8.         // 如果客户端没有发送数据,那么该线程就停滞不继续  
  9.         Socket socket = serverSocket.accept();  
  10.         // 从Socket当中得到InputStream对象  
  11.         InputStream inputStream = socket.getInputStream();  
  12.         byte buffer[] = new byte[1024 * 4];  
  13.         int temp = 0;  
  14.         // 从InputStream当中读取客户端所发送的数据  
  15.         while ((temp = inputStream.read(buffer)) != -1) {  
  16.             System.out.println(new String(buffer, 0, temp));  
  17.         }  
  18.         serverSocket.close();  
  19.     } catch (IOException e) {  
  20.         e.printStackTrace();  
  21.     }  
  22. }  

2、基于UDP协议

客户端发送数据实现:

[java] view plaincopy
  1. protected void connectServerWithUDPSocket() {  
  2.       
  3.     DatagramSocket socket;  
  4.     try {  
  5.         //创建DatagramSocket对象并指定一个端口号,注意,如果客户端需要接收服务器的返回数据,  
  6.         //还需要使用这个端口号来receive,所以一定要记住  
  7.         socket = new DatagramSocket(1985);  
  8.         //使用InetAddress(Inet4Address).getByName把IP地址转换为网络地址    
  9.         InetAddress serverAddress = InetAddress.getByName("192.168.1.32");  
  10.         //Inet4Address serverAddress = (Inet4Address) Inet4Address.getByName("192.168.1.32");    
  11.         String str = "[2143213;21343fjks;213]";//设置要发送的报文    
  12.         byte data[] = str.getBytes();//把字符串str字符串转换为字节数组    
  13.         //创建一个DatagramPacket对象,用于发送数据。    
  14.         //参数一:要发送的数据  参数二:数据的长度  参数三:服务端的网络地址  参数四:服务器端端口号   
  15.         DatagramPacket packet = new DatagramPacket(data, data.length ,serverAddress ,10025);    
  16.         socket.send(packet);//把数据发送到服务端。    
  17.     } catch (SocketException e) {  
  18.         e.printStackTrace();  
  19.     } catch (UnknownHostException e) {  
  20.         e.printStackTrace();  
  21.     } catch (IOException e) {  
  22.         e.printStackTrace();  
  23.     }    
  24. }  

客户端接收服务器返回的数据:

[java] view plaincopy
  1. public void ReceiveServerSocketData() {  
  2.     DatagramSocket socket;  
  3.     try {  
  4.         //实例化的端口号要和发送时的socket一致,否则收不到data  
  5.         socket = new DatagramSocket(1985);  
  6.         byte data[] = new byte[4 * 1024];  
  7.         //参数一:要接受的data 参数二:data的长度  
  8.         DatagramPacket packet = new DatagramPacket(data, data.length);  
  9.         socket.receive(packet);  
  10.         //把接收到的data转换为String字符串  
  11.         String result = new String(packet.getData(), packet.getOffset(),  
  12.                 packet.getLength());  
  13.         socket.close();//不使用了记得要关闭  
  14.         System.out.println("the number of reveived Socket is  :" + flag  
  15.                 + "udpData:" + result);  
  16.     } catch (SocketException e) {  
  17.         e.printStackTrace();  
  18.     } catch (IOException e) {  
  19.         e.printStackTrace();  
  20.     }  
  21. }  

服务器接收客户端实现:

[java] view plaincopy
  1. public void ServerReceviedByUdp(){  
  2.     //创建一个DatagramSocket对象,并指定监听端口。(UDP使用DatagramSocket)    
  3.     DatagramSocket socket;  
  4.     try {  
  5.         socket = new DatagramSocket(10025);  
  6.         //创建一个byte类型的数组,用于存放接收到得数据    
  7.         byte data[] = new byte[4*1024];    
  8.         //创建一个DatagramPacket对象,并指定DatagramPacket对象的大小    
  9.         DatagramPacket packet = new DatagramPacket(data,data.length);    
  10.         //读取接收到得数据    
  11.         socket.receive(packet);    
  12.         //把客户端发送的数据转换为字符串。    
  13.         //使用三个参数的String方法。参数一:数据包 参数二:起始位置 参数三:数据包长    
  14.         String result = new String(packet.getData(),packet.getOffset() ,packet.getLength());    
  15.     } catch (SocketException e) {  
  16.         e.printStackTrace();  
  17.     } catch (IOException e) {  
  18.         e.printStackTrace();  
  19.     }    
  20. }  


Http通信四种方式

一、Java接口--HttpURLConnection

1、get方式

     访问无需参数的网页 
Java代码  收藏代码
  1. //http地址  
  2.         String httpUrl = "http://192.168.1.110:8080/http1.jsp";  
  3.         //获得的数据  
  4.         String resultData = "";  
  5.         URL url = null;  
  6.         try  
  7.         {  
  8.             //构造一个URL对象  
  9.             url = new URL(httpUrl);   
  10.         }  
  11.         catch (MalformedURLException e)  
  12.         {  
  13.             Log.e(DEBUG_TAG, "MalformedURLException");  
  14.         }  
  15.         if (url != null)  
  16.         {  
  17.             try  
  18.             {  
  19.                 //使用HttpURLConnection打开连接  
  20.                 HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();  
  21.                 //得到读取的内容(流)  
  22.                 InputStreamReader in = new InputStreamReader(urlConn.getInputStream());  
  23.                 // 为输出创建BufferedReader  
  24.                 BufferedReader buffer = new BufferedReader(in);  
  25.                 String inputLine = null;  
  26.                 //使用循环来读取获得的数据  
  27.                 while (((inputLine = buffer.readLine()) != null))  
  28.                 {  
  29.                     //我们在每一行后面加上一个"\n"来换行  
  30.                     resultData += inputLine + "\n";  
  31.                 }           
  32.                 //关闭InputStreamReader  
  33.                 in.close();  
  34.                 //关闭http连接  
  35.                 urlConn.disconnect();  
  36.                 //设置显示取得的内容  
  37.                 if ( resultData != null )  
  38.                 {  
  39.                     mTextView.setText(resultData);  
  40.                 }  
  41.                 else   
  42.                 {  
  43.                     mTextView.setText("读取的内容为NULL");  
  44.                 }  
  45.             }  
  46.             catch (IOException e)  
  47.             {  
  48.                 Log.e(DEBUG_TAG, "IOException");  
  49.             }  
  50.         }  


2、post方式

当访问有参数的jsp网页时,只需要在url的末端加上参数即可,这是因为HttpURLConnection默认的访问方式为GET, 
url:http://192.168.1.110:8080/http1.jsp?par=values
当要以post方式访问时,需要设置进行setRequestMethod设置,如果无参数直接访问,有参数的话要通过writeBytes写入数据流。 
示例:
 

  1. try  
  2. {  
  3.     String httpUrl = "http://192.168.1.110:8080/httpget.jsp";  
  4.     // 使用HttpURLConnection打开连接  
  5.     HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();  
  6.     //因为这个是post请求,设立需要设置为true  
  7.     urlConn.setDoOutput(true);  
  8.     urlConn.setDoInput(true);  
  9.        // 设置以POST方式  
  10.     urlConn.setRequestMethod("POST");  
  11.        // Post 请求不能使用缓存  
  12.     urlConn.setUseCaches(false);  
  13.     urlConn.setInstanceFollowRedirects(true);  
  14.        // 配置本次连接的Content-type,配置为application/x-www-form-urlencoded的  
  15.     urlConn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");  
  16.        // 连接,从postUrl.openConnection()至此的配置必须要在connect之前完成,  
  17.        // 要注意的是connection.getOutputStream会隐含的进行connect。  
  18.     urlConn.connect();  
  19.     //DataOutputStream流  
  20.        DataOutputStream out = new DataOutputStream(urlConn.getOutputStream());  
  21.        //要上传的参数  
  22.        String content = "par=" + URLEncoder.encode("ABCDEFG""gb2312");  
  23.        //将要上传的内容写入流中  
  24.        out.writeBytes(content);   
  25.        //刷新、关闭  
  26.        out.flush();  
  27.        out.close();   
  28.        //获取数据  
  29.        BufferedReader reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));  
  30.     String inputLine = null;  
  31.     //使用循环来读取获得的数据  
  32.     while (((inputLine = reader.readLine()) != null))  
  33.     {  
  34.         //我们在每一行后面加上一个"\n"来换行  
  35.         resultData += inputLine + "\n";  
  36.     }           
  37.     reader.close();  
  38.     //关闭http连接  
  39.     urlConn.disconnect();  
  40.     //设置显示取得的内容  
  41.     if ( resultData != null )  
  42.     {  
  43.         mTextView.setText(resultData);  
  44.     }  
  45.     else   
  46.     {  
  47.         mTextView.setText("读取的内容为NULL");  
  48.     }  
  49. }  
  50. catch (IOException e)  
  51. {  
  52.     Log.e(DEBUG_TAG, "IOException");  
  53. }  

如果是下载一幅图片并显示,则将下载的InputStream转化为BitMap即可 
Java代码  收藏代码
  1. InputStream is=conn.getInputStream();  
  2. Bitmap bt=BitmapFactory.decodeStream(is);  
  3. return bt;.  

二、Apache接口--HttpClient

1、get方式

Java代码  收藏代码
  1. String httpUrl = "http://192.168.1.110:8080/httpget.jsp?par=HttpClient_android_Get";  
  2.         //HttpGet连接对象  
  3.         HttpGet httpRequest = new HttpGet(httpUrl);  
  4.         try  
  5.         {  
  6.             //取得HttpClient对象  
  7.             HttpClient httpclient = new DefaultHttpClient();  
  8.             //请求HttpClient,取得HttpResponse  
  9.             HttpResponse httpResponse = httpclient.execute(httpRequest);  
  10.             //请求成功  
  11.             if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)  
  12.             {  
  13.                 //取得返回的字符串  
  14.                 String strResult = EntityUtils.toString(httpResponse.getEntity());  
  15.                 mTextView.setText(strResult);  
  16.             }  
  17.             else  
  18.             {  
  19.                 mTextView.setText("请求错误!");  
  20.             }    
  21.         }  
  22.         catch (ClientProtocolException e)  
  23.         {  
  24.             mTextView.setText(e.getMessage().toString());  
  25.         }  

2、post方式

Java代码  收藏代码
  1. String httpUrl = "http://192.168.1.110:8080/httpget.jsp";  
  2.         //HttpPost连接对象  
  3.         HttpPost httpRequest = new HttpPost(httpUrl);  
  4.         //使用NameValuePair来保存要传递的Post参数  
  5.         List<NameValuePair> params = new ArrayList<NameValuePair>();  
  6.         //添加要传递的参数  
  7.         params.add(new BasicNameValuePair("par""HttpClient_android_Post"));  
  8.         try  
  9.         {  
  10.             //设置字符集  
  11.             HttpEntity httpentity = new UrlEncodedFormEntity(params, "gb2312");  
  12.             //请求httpRequest  
  13.             httpRequest.setEntity(httpentity);  
  14.             //取得默认的HttpClient  
  15.             HttpClient httpclient = new DefaultHttpClient();  
  16.             //取得HttpResponse  
  17.             HttpResponse httpResponse = httpclient.execute(httpRequest);  
  18.             //HttpStatus.SC_OK表示连接成功  
  19.             if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)  
  20.             {  
  21.                 //取得返回的字符串  
  22.                 String strResult = EntityUtils.toString(httpResponse.getEntity());  
  23.                 mTextView.setText(strResult);  
  24.             }  
  25.             else  
  26.             {  
  27.                 mTextView.setText("请求错误!");  
  28.             }  
  29.         }  
  30.         catch (ClientProtocolException e)  
  31.         {  
  32.             mTextView.setText(e.getMessage().toString());  
  33.         }  
  34. }
1 0
原创粉丝点击