我正在使用内置的HttpURLConnection
类发送一个简单的POST请求,但我想改变Java将标题与正文分开的方式(查看下面tcpflow -a port 80
的输出)。这是代码:
// Create HttpURLConnection object
URL url = new URL("http://httpbin.org/post");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// Set request method
connection.setRequestMethod("POST");
// Write body and "Content-Length" header
String body = "This+is+the+body+of+the+post+request.";
connection.setRequestProperty("Content-Length",
String.valueOf(body.length()));
connection.setDoOutput(true);
connection.getOutputStream().write(body.getBytes("US-ASCII"));
// Send request
int responseCode = connection.getResponseCode();
当我执行该代码并查看Java使用tcpflow -a port 80
实际发送的内容时(在端口80上打印所有请求/响应),我看到以下内容(我删除了响应):
192.168.178.113.54654-054.225.177.165.00080: POST /post HTTP/1.1
User-Agent: Java/9
Host: httpbin.org
Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Connection: keep-alive
Content-type: application/x-www-form-urlencoded
Content-Length: 37
192.168.178.113.54654-054.225.177.165.00080: This is the body of the post request.
标题是正确的,正文是正确的。但我可以看到身体是在一个单独的连接中转移的。我知道这是java.net.HttpURLConnection的问题,因为当我尝试使用Apache的HttpClient时,tcpflow -a port 80
给了我:
192.168.178.113.39708-054.243.202.193.00080: POST /post HTTP/1.1
Content-Length: 37
Host: httpbin.org
Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.5.3 (Java/9)
Accept-Encoding: gzip,deflate
This+is+the+body+of+the+post+request.
此处正文与标题一起发送,仅用/r/n/r/n
分隔。我希望Java库(java.net.HttpURLConnection
)也这样做。这可能吗?