该POST
方法不会在末尾添加换行符。您需要做的是Content-Length
在最后一个空行之后读取那么多字符。
例子
假设我们有以下HTML
页面:
<html>
<head/>
<body>
<form action="http://localhost:12345/test.php" method="POST">
<input type="hidden" name="postData" value="whatever"/>
<input type="hidden" name="postData2" value="whatever"/>
<input type="submit" value="Go"/>
</form>
</body>
</html>
现在我们启动一个非常简单的服务器,它在某种程度上类似于您的代码(这段代码充满了整体,但这不是问题):
public class Main {
public static void main(final String[] args) throws Exception {
final ServerSocket serverSocket = new ServerSocket(12345);
final Socket clientSocket = serverSocket.accept();
final InputStreamReader reader = new InputStreamReader(clientSocket.getInputStream());
final BufferedReader bufferedReader = new BufferedReader(reader);
int contentLength = -1;
while (true) {
final String line = bufferedReader.readLine();
System.out.println(line);
final String contentLengthStr = "Content-Length: ";
if (line.startsWith(contentLengthStr)) {
contentLength = Integer.parseInt(line.substring(contentLengthStr.length()));
}
if (line.length() == 0) {
break;
}
}
// We should actually use InputStream here, but let's assume bytes map
// to characters
final char[] content = new char[contentLength];
bufferedReader.read(content);
System.out.println(new String(content));
}
}
当我们在我们最喜欢的浏览器中加载页面并按下Go
按钮时,我们应该POST
在控制台中获取一些正文的内容。