现在的位置: 首页 > 综合 > 正文

Android网络编程原理及HttpURLConnection 用法

2012年05月19日 ⁄ 综合 ⁄ 共 5504字 ⁄ 字号 评论关闭
网络通信层次图

 

TCP报文段格式

 

 

建链过程中的“三次握手”

 

 

1、SYN(Synchronize Sequence Numbers)是TCP是传输控制协议中的一个标志位。如果该位被置为1,则表示这个报文是一个请求建立连接的报文。 
2、ACK(ACKnowledge Character)中文:确认字符。也是TCP是传输控制协议的一个标志位。在数据通信传输中,接收站发给发送站的一种传输控制字符。它表示确认发来的数据已经接受无误。是一个用于确认的报文。

 

关闭链路的四次握手

 

1、FIN(finish) 结束,没有更多的数据发送

 

 Http请求协议

GET /img/iknow/msg/msg.gif HTTP/1.1
Accept: */*
Referer: http://zhidao.baidu.com/
Accept-Language: zh-CN
User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; qdesk 2.5.1277.202; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; Tablet PC 2.0; .NET4.0C)
Accept-Encoding: gzip, deflate
Host: img.baidu.com
Connection: Keep-Alive
 

Http响应

HTTP/1.1 200 OK
Content-Type: image/gif
ETag: "1068122120"
Accept-Ranges: bytes
Last-Modified: Mon, 19 Dec 2011 08:00:44 GMT
Expires: Wed, 13 Jul 2022 12:27:55 GMT
Cache-Control: max-age=311040000
Content-Length: 1141
Date: Mon, 03 Sep 2012 12:27:55 GMT
Server: BWS/1.0

-----------------------------------------------------------------

HTTP/1.1 状态码 错误信息
Content-Type:  (类型)
Content-length:(包体长度)


HttpURLConnection Get请求 

复制代码
 1     /**
 2      * 1、android模拟器(simulator)把它自己作为了localhost,也就是说,代码中使用localhost或者127.0.0.1来访问,
 3      *          都是访问模拟器自己!
 4      * 2、如果想在模拟器simulator上面访问你的电脑,那么就使用android内置的IP 10.0.2.2 , 
 5      *    10.0.2.2 是模拟器设置的特定ip,是你的电脑的别名alias
 6      * 3、记住,在模拟器上用10.0.2.2访问你的电脑本机
 7      */
 8     private final String baseUrl = "http://10.0.2.2:8080/WebProj/main.jsp";
 9     
10     //HttpURLConnection Get请求
11      btnHttpURLConnection_Get.setOnClickListener(new OnClickListener()
12      {
13          @Override
14          public void onClick(View v)
15          {
16              InputStream is = null;
17              HttpURLConnection httpUrlConn = null;
18              try
19              {
20                  String strAccountNumber = etAccountNumber.getText().toString();
21                  String strPwd = etPwd.getText().toString();
22                  StringBuffer sbUrl = new StringBuffer();
23  
24                  //http://10.0.2.2:8080/WebProj/main.jsp?textAccountNumber=abc&textPwd=123
25                  sbUrl
26                      .append(baseUrl)
27                      .append("?textAccountNumber=")
28                      //注意如果参数是中文,要做以下处理
29                      .append(URLEncoder.encode(strAccountNumber, "utf-8"))
30                      .append("&textPwd=")
31                      .append(strPwd);
32  
33                  URL url = new URL(sbUrl.toString());
34                  //打开连接
35                  httpUrlConn = (HttpURLConnection) url.openConnection();
36                  //获取连接状态
37                  int rc = httpUrlConn.getResponseCode();
38                  
39                  //连接成功
40                  if(rc == HttpURLConnection.HTTP_OK)
41                  {
42                      //获取数据,先得到输入流
43                      is = httpUrlConn.getInputStream();
44                      
45                      BufferedReader buffer = new BufferedReader(new InputStreamReader(is,"gbk"));
46                      String inputLine = null;
47                      StringBuffer sbContent = new StringBuffer();
48  
49                      while ((inputLine = buffer.readLine()) != null)
50                      {
51                          sbContent.append(inputLine + "\n");
52                      }                
53                      
54                      //获取到的内容转换成 GBK 编码,防止中文乱码
55                      //String strContent = new String(sbContent.toString().getBytes("iso-8859-1"), "gbk");
56                      tvContent.setText(sbContent.toString());
57                      buffer.close();
58                      buffer = null;
59                  }
60              }
61              catch (MalformedURLException e)
62              {
63                  e.printStackTrace();
64              }
65              catch (IOException e)
66              {
67                  e.printStackTrace();
68              }
69              finally
70              {
71                  if(is != null)
72                  {
73                      try
74                      {
75                          is.close();
76                          is = null;
77                      }
78                      catch (IOException e)
79                      {
80                          e.printStackTrace();
81                      }
82                  }
83                  
84                  if(httpUrlConn != null)
85                  {
86                      //关闭连接
87                      httpUrlConn.disconnect();
88                      httpUrlConn = null;
89                  }
90              }
91          }
92      });
复制代码

 

HttpURLConnection Post请求

复制代码
  1     /**
  2      * 1、android模拟器(simulator)把它自己作为了localhost,也就是说,代码中使用localhost或者127.0.0.1来访问,
  3      *          都是访问模拟器自己!
  4      * 2、如果想在模拟器simulator上面访问你的电脑,那么就使用android内置的IP 10.0.2.2 , 
  5      *    10.0.2.2 是模拟器设置的特定ip,是你的电脑的别名alias
  6      * 3、记住,在模拟器上用10.0.2.2访问你的电脑本机
  7      */
  8     private final String baseUrl = "http://10.0.2.2:8080/WebProj/main.jsp";
  9     
 10     
 11     //HttpURLConnection Post请求
 12     btnHttpURLConnection_Post.setOnClickListener(new OnClickListener()
 13     {
 14         @Override
 15         public void onClick(View v)
 16         {
 17             DataOutputStream dos = null;
 18             InputStream is = null;
 19             HttpURLConnection httpUrlConn = null;
 20             try
 21             {
 22                 String strAccountNumber = etAccountNumber.getText().toString();
 23                 String strPwd = etPwd.getText().toString();
 24                 URL url = new URL(baseUrl);
 25                 //获取一个连接
 26                 httpUrlConn = (HttpURLConnection) url.openConnection();
 27                 //允许连接输出
 28                 httpUrlConn.setDoOutput(true);
 29                 //允许连接输入
 30                 httpUrlConn.setDoInput(true);
 31                 //设置以 POST 方式发送请求
 32                 httpUrlConn.setRequestMethod("POST");
 33                 //设置 POST 请求不能使用缓存
 34                 httpUrlConn.setUseCaches(false);
 35                 //设置这个连接是否可以重定向
 36                 httpUrlConn.setInstanceFollowRedirects(true);
 37                 //设置请求头的域的值
 38                 //配置本连接的 CONTENT_TYPE 为 application/x-www-form-urlencoded
 39                 httpUrlConn.setRequestProperty(HTTP.CONTENT_TYPE, URLEncodedUtils.CONTENT_TYPE);
 40                 //连接,所有的配置信息要 connect() 方法前完成,httpUrlConn.getOutputStream 会隐含地进行 connect
 41                 httpUrlConn.connect();
 42                 //构造请求包体的内容
 43                 StringBuffer sbParam = new StringBuffer();
 44                 //textAccountNumber=abc&textPwd=123
 45                 sbParam
 46                     .append("textAccountNumber=")
 47                     .append(URLEncoder.encode(strAccountNumber, "gbk"))
 48                     .append("&textPwd=")
 49                     .append(URLEncoder.encode(strPwd, "gbk"));
 50                 //获取连接的输出流
 51                 dos = new DataOutputStream(httpUrlConn.getOutputStream());
 52                 //将参数写入输出流
 53                 dos.writeBytes(sbParam.toString());
 54                 dos.flush();
 55                 dos.close();
 56                 dos = null;                    
 57                 
 58                 
 59                 //获取连接状态,当执行 getInputStream() 时,才将输出流中的数据发送出去
 60                 int rc = httpUrlConn.getResponseCode();//HttpURLConnection.HTTP_OK;
 61                 System.out.println("httpUrlConn.getResponseCode()=" + rc);
 62                 //连接成功
 63                 if(rc == HttpURLConnection.HTTP_OK)
 64                 {
 65                     //获取数据
 66                     is = httpUrlConn.getInputStream();
 67                     
 68                     BufferedReader buffer = new BufferedReader(new InputStreamReader(is,"gbk"));
 69                     String inputLine = null;
 70                     StringBuffer sbContent = new StringBuffer();
 71                     
 72                     while ((inputLine = buffer.readLine()) != null)
 73                     {
 74                         sbContent.append(inputLine + "\n");
 75                     }
 76                     
 77                     tvContent.setText(sbContent.toString());
 78                     buffer.close();
 79                     buffer = null;
 80                 }
 81             }
 82             catch (MalformedURLException e)
 83             {
 84                 e.printStackTrace();
 85             }
 86             catch (IOException e)
 87             {
 88                 e.printStackTrace();
 89             }
 90             finally
 91             {
 92                 if(dos != null)
 93                 {
 94                     try
 95                     {
 96                         dos.close();
 97                         dos = null;
 98                     }
 99                     catch (IOException e)
100                     {
101                         e.printStackTrace();
102                     }
103                 }
104             
105                 if(is != null)
106                 {
107                     try
108                     {
109                         is.close();
110                         is = null;
111                     }
112                     catch (IOException e)
113                     {
114                         e.printStackTrace();
115                     }
116                 }
117                 
118                 if(httpUrlConn != null)
119                 {
120                     //关闭连接
121                     httpUrlConn.disconnect();
122                     httpUrlConn = null;
123                 }
124             }
125         }
126     });
复制代码

 

 

 

抱歉!评论已关闭.