Android HttpURLConnection Socket Http (网络编程)

来源:互联网 发布:top域名免费注册 编辑:程序博客网 时间:2024/06/05 10:14

 欢迎转载,但请保留文章原始出处:
         CSDN
http://www.csdn.net
         雨季o莫忧离:http://blog.csdn.net/luckkof

正文

 


在Android的网络通讯中,通常会使用Socket进行设备间数的数据通讯,使用Http来对网络数据进行请求。
1、Socket(套接字)

不管是有过Java开发经验还是.NET开发经验的同学都应该对Socket有或多或少的了解,常见的TCP或者UDP协议其实都是基于Socket来实现的。

Socket是用于描述网络上的一个设备中的一个进程或者应用程序的,Socket由IP地址和端口号两部分组成。IP地址用来定位设备,端口号用来定位应用程序或者进程,比如我们常见的运行在80端口上的HTTP协议。Socket的常见格式为:192.168.1.1:1234。

那么应用程序是如何通过Socket来与网络中的其他设备进行通讯的呢?通常情况下,Socket通信有两部分,一部分为监听的Server端,一部分为主动请求连接的Client端。Server端会一直监听Socket中的端口直到有请求为止,当Client端对该端口进行连接请求时,Server端就给予应答并返回一个Socket对象,以后在Server端与Client端的数据交换就可以使用这个Socket来进行操作了。
2、Android中使用Socket进行数据交换 

ServerSocket
  建立服务端(Server)时,需要使用ServerSocket对象,这个对象会自动对其构造函数中传入的端口号进行监听,并在收到连接请求后,使用ServerSocket.accept()方法返回一个连接的的Socket对象。这个方法并不需要我们像在.NET中那样使用Start方法,它会自动进行监听的。

Socket
  不管建立客户端(Client)还是在进行其他数据交换方面的操作时,都需要使用Socket类。Socket类在进行初始化时需要出入Server端的IP地址和端口号,并返回连接到Server端的一个Socket对象,如果是连接失败,那么将返回异常。同ServerSocket,也是自动进行连接请求的。

,并返回连接到Server端的一个Socket对象,如果是连接失败,那么将返回异常。同ServerSocket,也是自动进行连接请求的。

通过上面两个步骤后,Server端和Client端就可以连接起来了,但是仅仅连接起来是没有任何作用的,数据交换才是我们的目的,这时候就需要用到IO流中的OutputStream类和InputStream类。
OutputStream——可写流
  当应用程序需要对流进行数据写操作时,可以使用Socket.getOutputStream()方法返回的数据流进行操作。
InputStream——可读流
  当应用程序要从流中取出数据时,可以使用Socket.getInputStream()方法返回的数据流进行操作。

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. <span style="font-size:10px;">View Code   
  2.  package LiB.Demo;  
  3.    
  4.  import java.io.BufferedReader;  
  5.  import java.io.BufferedWriter;  
  6.  import java.io.IOException;  
  7.  import java.io.InputStreamReader;  
  8.  import java.io.OutputStreamWriter;  
  9.  import java.net.ServerSocket;  
  10.  import java.net.Socket;  
  11.    
  12.  public class SocketHelper {  
  13.      private static ServerSocket serverSocket = null;  
  14.      private static Socket client = null;  
  15.      private final static int port = 9048;  
  16.      private static BufferedReader br= null;   
  17.      private static BufferedWriter bw = null;  
  18.        
  19.      /** 
  20.       * 创建一个SocketServer对象用来建立服务器 
  21.       * @throws IOException 
  22.  */  
  23.      public static void CreateServer() throws IOException  
  24.      {  
  25.          serverSocket = new ServerSocket(port,10);  
  26.          System.out.println("start listening...");  
  27.      }  
  28.        
  29.      /** 
  30.       * 创建一个Socket对象用来连接SocketServer对象 
  31.       * @param dstName Server对象的ip地址 
  32.       * @return  
  33.       * @throws IOException 
  34.  */  
  35.      public static Socket CreateClient(String dstName) throws IOException  
  36.      {  
  37.          Socket socket = new Socket(dstName, port);  
  38.          //Socket sockets = new Socket("192.168.8.12",port);  
  39.          return socket;  
  40.      }  
  41.        
  42.      /** 
  43.       * 返回一个已经连接到服务器上的Socket对象 
  44.       * @throws IOException 
  45.  */  
  46.      public static void GetClinetSocket() throws IOException  
  47.      {  
  48.          client = serverSocket.accept();  
  49.          System.out.println("get a connected client");  
  50.      }  
  51.        
  52.      /** 
  53.       * 向socket对象所获取的流中发送数据 
  54.       * @param socket 
  55.       * @param msg 
  56.       * @throws IOException 
  57.  */  
  58.      public static void SendMsg(Socket socket , String msg) throws IOException  
  59.      {  
  60.          bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));  
  61.          bw.write(msg);  
  62.          bw.flush();  
  63.          bw.close();  
  64.      }  
  65.        
  66.      /** 
  67.       * 获取socket对象流中数据 
  68.       * @param socket 
  69.       * @param msg 
  70.       * @return 
  71.       * @throws IOException 
  72.  */  
  73.      public static String ReceiveMsg(Socket socket, String msg) throws IOException  
  74.      {  
  75.          br = new BufferedReader(new InputStreamReader(socket.getInputStream()));  
  76.          String receiveMsg = "Receive msg:"+ br.readLine();  
  77.          br.close();  
  78.          return receiveMsg;  
  79.      }  
  80.        
  81.      /** 
  82.       * 释放socket对象 
  83.       * @throws IOException 
  84.  */  
  85.      public static void Close() throws IOException  
  86.      {  
  87.          if(client != null)  
  88.          {  
  89.              client.close();  
  90.          }  
  91.          if(serverSocket != null)  
  92.          {  
  93.              serverSocket.close();  
  94.          }  
  95.      }  
  96.  }</span>  
3、HTTP通讯
  在开始前先简单介绍下HTTP协议中的两种不同的请求方式——GET和POST。GET方式在进行数据请求时,会把数据附加到URL后面传递给服务器,比如常见的:http://XXX.XXX.XXX/XX.aspx?id=1,POST方式则是将请求的数据放到HTTP请求头中,作为请求头的一部分传入服务器。所以,在进行HTTP编程前,首先要明确究竟使用的哪种方式进行数据请求的。
  在Android中,可以有两种方式可以用来进行Http编程:1、HttpURLConnection;2、HttpClient。
HttpURLConnection
  HttpURLConnection是继承自URLConnection的一个抽象类,在HTTP编程时,来自HttpURLConnection的类是所有操作的基础,获取该对象的代码如下:
[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. <span style="font-size:10px;">View Code   
  2.      public HttpURLConnection urlconn= null;  
  3.      private void Init() throws IOException  
  4.      {  
  5.          if (urlStr=="")  
  6.          {  
  7.              urlStr="http://www.baidu.com";  
  8.          }  
  9.          URL url = new URL(urlStr);  
  10.          //打开一个URL所指向的Connection对象  
  11.          urlconn = (HttpURLConnection)url.openConnection();  
  12.      }</span>  

HttpURLConnection对网络资源的请求在默认情况下是使用GET方式的,所以当使用GET方式时,不需要我们做太多的工作:

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. <span style="font-size:10px;">View Code   
  2.      public HttpURLConnection urlconn= null;  
  3.      private void Init() throws IOException  
  4.      {  
  5.          if (urlStr=="")  
  6.          {  
  7.              urlStr="http://www.baidu.com";  
  8.          }  
  9.          URL url = new URL(urlStr);  
  10.          //打开一个URL所指向的Connection对象  
  11.          urlconn = (HttpURLConnection)url.openConnection();  
  12.      }  
  13.      /** 
  14.       * Http中的get请求,在Url中带有请求的参数,请求的URL格式通常为:"http://XXX.XXXX.com/xx.aspx?param=value" 
  15.       * 在android中默认的http请求为get方式 
  16.       * @return 
  17.       * @throws IOException 
  18.  */  
  19.      public String HttpGetMethod() throws IOException  
  20.      {  
  21.          if(urlconn == null)  
  22.          {  
  23.              Init();  
  24.          }  
  25.          String result = StreamDeal(urlconn.getInputStream());  
  26.          urlconn.disconnect();  
  27.          return result;  
  28.      }</span>  

当我们需要使用POST方式时,就需要使用setRequestMethod()来设置请求方式了。

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. <span style="font-size:10px;">View Code   
  2.      /** 
  3.       * Http中的post请求,不在Url中附加任何参数,这些参数都会通过cookie或者session等其他方式以键值对的形式key=value传送到服务器上,完成一次请求 
  4.       * 请求的URL格式通常为:"http://XXX.XXXX.com/xx.aspx" 
  5.       * @param param 请求的键名 
  6.       * @param value 请求的数据值 
  7.       * @throws IOException 
  8.  */  
  9.      public String HttpPostMethod(String key,String value) throws IOException  
  10.      {  
  11.          if (urlconn==null)  
  12.          {  
  13.              Init();  
  14.          }  
  15.          //设置该URLConnection可读  
  16.          urlconn.setDoInput(true);  
  17.          //设置该URLConnection可写  
  18.          urlconn.setDoOutput(true);  
  19.          //使用POST方式来提交数据  
  20.          urlconn.setRequestMethod("POST");  
  21.          //不运行缓存  
  22.          urlconn.setUseCaches(false);  
  23.          //当使用POST方式进行数据请求时,我们可以手动执行connect动作,当然,这个动作其实在getOutputStream()方法中会默认执行的  
  24.  //上面那些设置URLConnection属性的动作,一定要在connect动作执行前,因为一旦动作已经执行,熟悉设置就没有任何作用了  
  25.          urlconn.connect();  
  26.          //使用POST方式时,我们需要自己构造部分Http请求的内容,因此我们需要使用OutputStream来进行数据写如操作  
  27.          OutputStreamWriter writer = new OutputStreamWriter(urlconn.getOutputStream());  
  28.            
  29.          String urlQueryStr = key+"="+URLEncoder.encode(value, "Utf-8");  
  30.          writer.write(urlQueryStr);  
  31.            
  32.          writer.flush();  
  33.          writer.close();  
  34.          //获取返回的内容  
  35.          String result = StreamDeal(urlconn.getInputStream());  
  36.          return result;  
  37.            
  38.      }</span>  

HttpClient
  这个类并不是来自Android的,而是来自org.apache.http。和HttpURLConnection相同,HttpClient也存在GET和POST两种方式。
HttpGet
      在HttpClient中,我们可以非常轻松使用HttpGet对象来通过GET方式进行数据请求操作,当获得HttpGet对象后我们可以使用HttpClient的execute方法来向我们的服务器发送请求。在发送的GET请求被服务器相应后,会返回一个HttpResponse响应对象,利用这个响应的对象我们能够获得响应回来的状态码,如:200、400、401等等。
[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. <span style="font-size:10px;">View Code   
  2.      public String HttpGetMethod()  
  3.      {  
  4.          String result = "";  
  5.          try  
  6.          {  
  7.          HttpGet httpRequest = new HttpGet(urlStr);  
  8.          HttpClient httpClient = new DefaultHttpClient();  
  9.          HttpResponse httpResponse = httpClient.execute(httpRequest);  
  10.          if(httpResponse.getStatusLine().getStatusCode()==HttpStatus.SC_OK)  
  11.          {  
  12.              result = EntityUtils.toString(httpResponse.getEntity());  
  13.          }  
  14.          else  
  15.          {  
  16.              result = "null";  
  17.          }  
  18.          return result;  
  19.          }  
  20.          catch(Exception e)  
  21.          {  
  22.              return null;  
  23.          }  
  24.      }</span>  
HttpPost

      当我们使用POST方式时,我们可以使用HttpPost类来进行操作。当获取了HttpPost对象后,我们就需要向这个请求体传入键值对,这个键值对我们可以使用NameValuePair对象来进行构造,然后再使用HttpRequest对象最终构造我们的请求体,最后使用HttpClient的execute方法来发送我们的请求,并在得到响应后返回一个HttpResponse对象。其他操作和我们在HttpGet对象中的操作一样。

[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. <span style="font-size:10px;">View Code   
  2.  public String HttpPostMethod(String key,String value)  
  3.      {  
  4.          String result = "";  
  5.          try  
  6.          {  
  7.          // HttpPost连接对象  
  8.          HttpPost httpRequest = new HttpPost(urlStr);  
  9.          // 使用NameValuePair来保存要传递的Post参数  
  10.          List<NameValuePair> params = new ArrayList<NameValuePair>();  
  11.          // 添加要传递的参数  
  12.          params.add(new BasicNameValuePair(key, value));  
  13.          // 设置字符集  
  14.          HttpEntity httpentity = new UrlEncodedFormEntity(params, "Utf-8");  
  15.          // 请求httpRequest  
  16.          httpRequest.setEntity(httpentity);  
  17.          // 取得默认的HttpClient  
  18.          HttpClient httpclient = new DefaultHttpClient();  
  19.          // 取得HttpResponse  
  20.          HttpResponse httpResponse = httpclient.execute(httpRequest);  
  21.          // HttpStatus.SC_OK表示连接成功  
  22.          if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {  
  23.              // 取得返回的字符串  
  24.              result = EntityUtils.toString(httpResponse.getEntity());  
  25.              return result;   
  26.          } else {  
  27.               return "null";  
  28.          }  
  29.          }  
  30.          catch(Exception e)  
  31.          {  
  32.              return null;  
  33.          }  
  34.      }</span>  
0 0