使用HttpURLConnection更改header-body-separator(来自java.net)

时间:2017-12-01 14:17:32

标签: java http post httpurlconnection

我正在使用内置的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)也这样做。这可能吗?

编辑:我发现服务器拒绝我的请求的原因并不是主体是在一个不同的数据包(数据包,而不是连接,如Julian Reschke所指出的)而不是标题但只是我发送了错误的数据< EM>捂脸。

0 个答案:

没有答案