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

时间:2011-12-10 11:00:25

标签: java http post http-headers multipartform-data

我正在向服务器发出HTTP POST查询,我正在手动创建帖子正文。 我认为我在内容长度标题上犯了一些错误,因为在服务器端,当我在开始时得到http响应时,我看到带有http响应200的标题然后在我的php脚本中我打印了post参数和文件名我得到正确的值,但加上一些垃圾字节。 这是我的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--"
);

这是服务器的输出(忽略[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

服务器上的php脚本就像你能想到的一样简单:

<?php 
    print_r($_POST) ;
?>

2 个答案:

答案 0 :(得分:2)

来自HTTP RFC(RFC2626, 14.3

  

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

换句话说,你应该计算字节数(octets),因此\r\n应该被认为是2个八位字节/字节。

答案 1 :(得分: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
);

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