http请求与响应的协议格式在前一篇文章中已经介绍过了,并对get请求进行了模拟测试,下面就对post请求进行测试。
1.首先搭建测试环境:
新建个web项目posttest,编写一个servlet与html页面来进行post访问:
LoginServlet:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(name="login",urlPatterns={"/login"})
public class LoginServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
String name=req.getParameter("name");
String pwd = req.getParameter("pwd");
if(name.equals("hello")&&pwd.equals("world")) {
out.print("welcome," + name);
} else {
out.print("sorry, access denied");
}
out.flush();
}
}
login.html:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="login" method="post">
name :
<input type="text" name="name" /> <br/>
password:
<input type="password" name="pwd" /> <br/>
<input type="submit" value="submit"/>
</form>
</body>
</html>
运行项目,截包:
返回数据包:
2.编程模拟:
public class PostDate {
public static void main(String[] args) throws UnknownHostException, IOException {
Socket socket = new Socket("127.0.0.1",8080);
String requestLine="POST /posttest/login HTTP/1.1\r\n";
String host="Host: localhost:8080\r\n";
String contentType="Content-Type: application/x-www-form-urlencoded\r\n";
String body = "name=hello&pwd=world";
// String contentLength="Content-Length: "+body.length()+"\r\n";
OutputStream os = socket.getOutputStream();
os.write(requestLine.getBytes());
os.write(host.getBytes());
os.write(contentType.getBytes());
// os.write(contentLength.getBytes());
os.write("\r\n".getBytes());
os.write(body.getBytes());
os.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String tmp = null;
while((tmp=reader.readLine())!=null) {
System.out.println(tmp);
}
socket.close();
}
}
注意,如果直接运行将不能完成请求,并导致服务器出现异常,返回500状态码(内部程序错误),发送的数据包如下 :
这是因为请求数据不完整造成的。若要使程序运行,需加上Content-Length请求头(上面程序中被注释掉的内容)。