http協議之post請求(socket請求web內容)

http請求與響應的協議格式在前一篇文章中已經介紹過了,並對get請求進行了模擬測試,下面就對post請求進行測試。html

1.首先搭建測試環境:java

新建個web項目posttest,編寫一個servlet與html頁面來進行post訪問:web

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>

運行項目,截包:app


返回數據包:socket

2.編程模擬:ide


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狀態碼(內部程序錯誤),發送的數據包以下 :post


這是由於請求數據不完整形成的。若要使程序運行,需加上Content-Length請求頭(上面程序中被註釋掉的內容)。測試

相關文章
相關標籤/搜索