前言
说到HTTP协议,那必须要说说WWW了,WWW是环球信息网(World Wide Web )的缩写,也可以简称为Web,中文名字为“万维网”。简单来说,WWW是以Internet作为传输媒介的一个应用系统,WWW网上基本的传输单位是Web网页。WWW的工作是基于B/S模型,由Web浏览器和Web服务器构成,两者之间采用超文本传输协议HTTP协议进行通信。
HTTP协议是基于TCP/IP协议之上的协议,是Web浏览器和Web服务器之间的应用层的协议,是通用的、无状态的面向对象的协议。关于HTTP协议的详细讲解,请参见博客:HTTP协议详解,里面讲解的很清楚,这里主要是说明HTTP在Java中的应用,为从其他技术下转向Android开发打好基础。
首先普及一下网络协议的知识,数据在Internet上传输,一般通过三种协议来实现发送信息和实现:
HTTP协议,也是在工作中最常用的,是建立在TCP/IP基础上实现的。
FTP协议。
TCP/IP协议,它也是最低层的协议,其它的方式必须要通过它,但是想要实现这种协议必须要实现socket编程,这种方法是用来上传一些比较大的文件,视频,进行断电续传的操作。
HTTP协议
下面详细讲解一下HTTP协议,因为HTTP是无状态的协议,所以服务端并不记录客户端之前发送信息,一码归一码,所以HTTP协议使用报文头的形式记录状态,一般分为请求报文和响应报文。一般用户使用浏览器访问网页,是无需关心HTTP请求的报文头的,因为开发人员已经浏览器已经帮忙处理了,但是当进行开发工作的时候,这些是必须要了解的。
对于报文,一般关心请求方式,是GET或者是POST;请求数据类型,是文本还是音频;数据的编码格式,一般用utf-8;发送的数据长度;响应返回码,一般200为成功,其他响应码都是有问题。具体了解还是看看上面推荐的博客。
HTTP/1.1协议中一共定义了八种方法(有时也叫“动作”)来表明Request-URI指定的资源的不同操作方式,但是一般常用的就是GET和POST方式。
这里简单说一下GET方式和POST方式的差别:
GET是从服务器上获取数据,POST是向服务器传送数据。
在客户端,GET方式在通过URL提交数据,数据在URL中可以看到;POST方式,数据放在HTML HEADER内提交。
对于GET方式,服务器端用Request.QueryString获取变量的值,对于POST方式,服务器用Request.Form获取提交的数据。
GET方式提交的数据不能大于2KB(主要是URL长度限制),而POST则没有此限制。
安全性问题。正如2中提到,使用GET的时候,参数会显示在地址栏上,而POST不会。所以,如果这些数据是中文数据而且是非敏感数据,那么使用GET;如果用户输入的数据不是中文字符而且包含敏感数据,那么还是使用POST为好。
Java中使用HTTP
下面通过两个例子来分别讲解一下GET和POST在Java中的使用,如果在Java中需要使用HTTP协议进行访问,一般通过HttpURLConnection类来实现。
HttpURLConnection继承了URLConnection,所以在URLConnection的基础上进一步改进,增加了一些用于操作HTTP资源的便捷方法。Java中HttpURLConnection对象通过URL.openConnection()方法来获得,需要进行强制转换。先来介绍几个HttpURLConnection的常用方法:
void setConnectTimeout(int timeout):设置连接超时时长,如果超过timeout时长,则放弃连接,单位以毫秒计算。
void setDoInput(boolean newValue) :标志是否允许输入。
void setDoOutput(boolean newValue):标志是否允许输出。
String getRequestMethod():获取发送请求的方法。
int getResponseCode():获取服务器的响应码。
void setRequestMethod(String method):设置发送请求的方法。
void setRequestProperty(String field,String newValue):设置请求报文头,并且只对当前HttpURLConnection有效。
GET方式
这个例子通过GET方式从服务端获取一张图片的信息,并把其保存在本地磁盘中。服务器为本机上的IIS,一张静态图片,直接通过URL访问。
直接上Java代码,注释已经解释的很清楚了。

1 package com.http.get;
2
3 import java.io.FileOutputStream;
4 import java.io.IOException;
5 import java.io.InputStream;
6 import java.net.HttpURLConnection;
7 import java.net.MalformedURLException;
8 import java.net.URL;
9
10 public class HttpUtils {
11 private static String URL_PATH = "http://192.168.1.106:8080/green.jpg";
12 /**
13 * @param args
14 */
15 public static void main(String[] args) {
16 // 调用方法获取图片并保存
17 saveImageToDisk();
18 }
19 /**
20 * 通过URL_PATH的地址访问图片并保存到本地
21 */
22 public static void saveImageToDisk()
23 {
24 InputStream inputStream= getInputStream();
25 byte[] data=new byte[1024];
26 int len=0;
27 FileOutputStream fileOutputStream=null;
28 try {
29 //把图片文件保存在本地F盘下
30 fileOutputStream=new FileOutputStream("F:\\test.png");
31 while((len=inputStream.read(data))!=-1)
32 {
33 //向本地文件中写入图片流
34 fileOutputStream.write(data,0,len);
35 }
36 } catch (IOException e) {
37 e.printStackTrace();
38 }
39 finally
40 {
41 //最后关闭流
42 if(inputStream!=null)
43 {
44 try {
45 inputStream.close();
46 } catch (IOException e) {
47 e.printStackTrace();
48 }
49 }
50 if(fileOutputStream!=null)
51 {
52 try {
53 fileOutputStream.close();
54 } catch (IOException e) {
55 e.printStackTrace();
56 }
57 }
58 }
59 }
60 /**
61 * 通过URL获取图片
62 * @return URL地址图片的输入流。
63 */
64 public static InputStream getInputStream() {
65 InputStream inputStream = null;
66 HttpURLConnection httpURLConnection = null;
67
68 try {
69 //根据URL地址实例化一个URL对象,用于创建HttpURLConnection对象。
70 URL url = new URL(URL_PATH);
71
72 if (url != null) {
73 //openConnection获得当前URL的连接
74 httpURLConnection = (HttpURLConnection) url.openConnection();
75 //设置3秒的响应超时
76 httpURLConnection.setConnectTimeout(3000);
77 //设置允许输入
78 httpURLConnection.setDoInput(true);
79 //设置为GET方式请求数据
80 httpURLConnection.setRequestMethod("GET");
81 //获取连接响应码,200为成功,如果为其他,均表示有问题
82 int responseCode=httpURLConnection.getResponseCode();
83 if(responseCode==200)
84 {
85 //getInputStream获取服务端返回的数据流。
86 inputStream=httpURLConnection.getInputStream();
87 }
88 }
89
90 } catch (MalformedURLException e) {
91 e.printStackTrace();
92 } catch (IOException e) {
93 e.printStackTrace();
94 }
95 return inputStream;
96 }
97
98 }
POST方式
这个例子通过POST方式访问一个登陆页面,需要输入用户名(username)和密码(password)。虽然这里使用的Java在讲解问题,但是服务端是使用.Net的框架,一个很简单的HTML页面加一个表单传送的一般处理程序,输入为admin+123为登陆成功,这里不累述了。
Java代码:

1 package com.http.post;
2
3 import java.io.ByteArrayOutputStream;
4 import java.io.IOException;
5 import java.io.InputStream;
6 import java.io.OutputStream;
7 import java.io.UnsupportedEncodingException;
8 import java.net.HttpURLConnection;
9 import java.net.URL;
10 import java.net.URLEncoder;
11 import java.util.HashMap;
12 import java.util.Map;
13
14 public class postUtils {
15
16 private static String PATH = "http://192.168.222.1:1231/loginas.ashx";
17 private static URL url;
18
19 public postUtils() {
20 }
21 static {
22 try {
23 url = new URL(PATH);
24 } catch (Exception e) {
25 e.printStackTrace();
26 }
27 }
28
29 /**
30 * 通过给定的请求参数和编码格式,获取服务器返回的数据
31 * @param params 请求参数
32 * @param encode 编码格式
33 * @return 获得的字符串
34 */
35 public static String sendPostMessage(Map<String, String> params,
36 String encode) {
37 StringBuffer buffer = new StringBuffer();
38 if (params != null && !params.isEmpty()) {
39 for (Map.Entry<String, String> entry : params.entrySet()) {
40 try {
41 buffer.append(entry.getKey())
42 .append("=")
43 .append(URLEncoder.encode(entry.getValue(), encode))
44 .append("&");//请求的参数之间使用&分割。
45 } catch (UnsupportedEncodingException e) {
46 e.printStackTrace();
47 }
48
49 }
50 buffer.deleteCharAt(buffer.length() - 1);
51 System.out.println(buffer.toString());
52 try {
53 HttpURLConnection urlConnection = (HttpURLConnection) url
54 .openConnection();
55 urlConnection.setConnectTimeout(3000);
56 //设置允许输入输出
57 urlConnection.setDoInput(true);
58 urlConnection.setDoOutput(true);
59 byte[] mydata = buffer.toString().getBytes();
60 //设置请求报文头,设定请求数据类型
61 urlConnection.setRequestProperty("Content-Type",
62 "application/x-www-form-urlencoded");
63 //设置请求数据长度
64 urlConnection.setRequestProperty("Content-Length",
65 String.valueOf(mydata.length));
66 //设置POST方式请求数据
67 urlConnection.setRequestMethod("POST");
68 OutputStream outputStream = urlConnection.getOutputStream();
69 outputStream.write(mydata);
70 int responseCode = urlConnection.getResponseCode();
71 if (responseCode == 200) {
72 return changeInputStream(urlConnection.getInputStream(),
73 encode);
74 }
75 } catch (IOException e) {
76 e.printStackTrace();
77 }
78 }
79 return "";
80 }
81
82 /**
83 * 把服务端返回的输入流转换成字符串格式
84 * @param inputStream 服务器返回的输入流
85 * @param encode 编码格式
86 * @return 解析后的字符串
87 */
88 private static String changeInputStream(InputStream inputStream,
89 String encode) {
90 ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
91 byte[] data = new byte[1024];
92 int len = 0;
93 String result="";
94 if (inputStream != null) {
95 try {
96 while ((len = inputStream.read(data)) != -1) {
97 outputStream.write(data,0,len);
98 }
99 result=new String(outputStream.toByteArray(),encode);
100
101 } catch (IOException e) {
102 e.printStackTrace();
103 }
104 }
105 return result;
106 }
107
108 /**
109 * @param args
110 */
111 public static void main(String[] args) {
112 //通过Map设置请求字符串。
113 Map<String, String> params = new HashMap<String, String>();
114 params.put("username", "admin");
115 params.put("password", "123");
116 String result=sendPostMessage(params, "utf-8");
117 System.out.println(result);
118 }
119
120 }
以上内容来源于互联网