http协议之post请求(socket请求web内容)

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请求头(上面程序中被注释掉的内容)。


转载于:https://my.oschina.net/wisedream/blog/128049

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值