HTTP POST查询如何计算内容长度

gos*_*vka 5 java post http multipartform-data http-headers

我正在对服务器进行HTTP POST查询,并且正在手动创建帖子正文。我认为我对content-length标头犯了一些错误,因为在服务器端,当我在开始时获得http响应时,我看到标头为http响应200,然后在我的php脚本中打印后参数和文件名我得到正确的值,但还有一些垃圾字节。这是我的http帖子的正文:

StringBuffer str = new StringBuffer();
str.append("POST /tst/query.php HTTP/1.1\r\n"
        + "Host: myhost.com\r\n"
        + "User-Agent: sampleAgent\r\n"
        + "Content-type: multipart/form-data, boundary=AaB03x\r\n" 
        + "Content-Length: 172\r\n\r\n"
        + "--AaB03x\r\n"
        + "content-disposition: form-data; name=\"asd\"\r\n\r\n123\r\n--AaB03x\r\n"
        + "content-disposition: form-data; name=\"pics\"; filename=\"file1.txt\"\r\n"
        + "Content-Type: text/plain\r\n\r\n555\r\n"
        + "--AaB03x--"
);
Run Code Online (Sandbox Code Playgroud)

这是服务器的输出(忽略[0.0]-来自我打印结果的控制台)

[0.0] HTTP/1.1 200 OK

[0.0] Date: Sat, 10 Dec 2011 11:53:11 GMT

[0.0] Server: Apache

[0.0] Transfer-Encoding: chunked

[0.0] Content-Type: text/html

[0.0] 

[0.0] 6

[0.0] Array
[0.0] 

[0.0] 2

[0.0] (
[0.0] 

[0.0] 1

[0.0]  

[0.0] 1

[0.0]  

[0.0] 1

[0.0]  

[0.0] 1

[0.0]  

[0.0] 1

[0.0] [

[0.0] 3

[0.0] asd

[0.0] 5

[0.0] ] => 

3
123
1
2
)
0
Run Code Online (Sandbox Code Playgroud)

和服务器上的php脚本一样,您可以想到:

<?php 
    print_r($_POST) ;
?>
Run Code Online (Sandbox Code Playgroud)

Fil*_*efp 5

来自 HTTP RFC ( RFC2626, 14.3 )

Content-Length entity-header 字段指示发送给接收者的实体主体的大小,以十进制的 OCTET 数表示,或者在 HEAD 方法的情况下,本应发送的实体主体的大小请求是 GET。

换句话说,您应该计算字节数 ( octets),因此\r\n应将其视为 2 个八位字节/字节。


Dav*_*dom 2

String boundary = "AaB03x";
String body = "--" + boundary + "\r\n"
            + "Content-Disposition: form-data; name=\"asd\"\r\n"
            + "\r\n"
            + "123\r\n"
            + "--" + boundary + "\r\n"
            + "Content-Disposition: form-data; name=\"pics\"; filename=\"file1.txt\"\r\n"
            + "Content-Type: text/plain\r\n"
            + "\r\n"
            + "555\r\n"
            + "--" + boundary + "--";

StringBuffer str = new StringBuffer();
str.append("POST /tst/query.php HTTP/1.1\r\n"
         + "Host: myhost.com\r\n"
         + "User-Agent: sampleAgent\r\n"
         + "Content-type: multipart/form-data, boundary=\"" + boundary + "\"\r\n" 
         + "Content-Length: " + body.length() + "\r\n"
         + "\r\n"
         + body
);
Run Code Online (Sandbox Code Playgroud)

...我想说的是应该这样做