要弄懂HTTP协议,首先得知道HTTP请求和响应消息格式:
HTTP请求消息:
组成要素:一个起始行(也叫请求行(request line))、一个或多个头域(也叫请求头(header))、一个指示头域结束的空行、可选的消息体(也叫请求数据)
例如:(ie浏览器请求信息)
POST / HTTP/1.1
Accept: text/html, application/xhtml+xml, */*
Accept-Language: zh-CN
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko
Content-Type: application/x-www-form-urlencoded
Accept-Encoding: gzip, deflate
Host: localhost:8090
Content-Length: 19
Connection: Keep-Alive
Cache-Control: no-cache
myname=tom&myage=20
java程序通过Socket编程获取浏览器端发起的HTTP请求,请求方法 POST:
public class HttpServer {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(8090);
while(true){
Socket socket = serverSocket.accept();
InputStream in = socket.getInputStream();
InputStreamReader inr = new InputStreamReader(in);
int ch;
while((ch = inr.read()) != -1){//此方式不会在出现空行的时候悬停
System.out.print((char)ch);
}
response(socket);
System.out.println("current user closed the session!");
inr.close();
in.close();
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
HTTP响应消息:
组成要素:一个起始行(也叫请求行(request line))、一个或多个头域(也叫请求头(header))、一个指示头域结束的空行、响应消息(也叫响应数据)
例如:(百度主页的响应信息)
HTTP/1.1 200 OK
Date: Wed, 09 Nov 2016 07:57:41 GMT
Server: Apache
P3P: CP=" OTI DSP COR IVA OUR IND COM "
Set-Cookie: BAIDUID=6A8EC1971522086F5CD1DE0C1ED46A00:FG=1; expires=Thu, 09-Nov-17 07:57:41 GMT; max-age=31536000; path=/; domain=.baidu.com; version=1
Last-Modified: Thu, 12 Mar 2015 07:58:59 GMT
ETag: "47b-51112c19e16c0"
Accept-Ranges: bytes
Cache-Control: max-age=86400
Expires: Thu, 10 Nov 2016 07:57:41 GMT
Vary: Accept-Encoding,User-Agent
Content-Encoding: gzip
Content-Length: 561
Connection: Keep-Alive
Content-Type: text/html
?(返回消息体暂未解决流的编码问题)
java代码获取指定web服务器响应消息:
public class MyHttpClient {
public static void main(String[] args) throws Exception{
InetAddress inet = InetAddress.getByName("localhost"); //使用本机的web应用程序做测试
System.out.println(inet.getHostAddress());
Socket socket = new Socket(inet.getHostAddress(),8080);
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf-8")); //获取输入流,并设置编码格式为utf-8
PrintWriter writer = new PrintWriter(out);
writer.println("GET /prac/err.html HTTP/1.1");
writer.println("Accept: text/html, application/xhtml+xml, */*");
writer.println("Accept-Encoding: gzip, deflate");
writer.println("Host: localhost");
writer.println("User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko");
writer.println("Connection: Keep-Alive");
writer.println("content-type: text/html;charset=utf-8");//告诉web服务器,本客户端只能处理utf-8编码的字符
writer.println(); //请求消息里面或有一行空行
writer.flush();
String line = reader.readLine();
OutputStreamWriter fw = new OutputStreamWriter(new FileOutputStream("resp.html"));
while(line != null){
System.out.println(line);
fw.write(line);
fw.flush();
line = reader.readLine();
}
reader.close();
writer.close();
fw.close();
socket.close();
}
}