Search code examples
javahttpposthttp-headersmultipartform-data

HTTP POST query how to calculate content length


I am making a HTTP POST query to a server and I am creating the post body manually. I think I am making some mistake with the content-length header because on the server side when I get the http response at the beginning I see the headers with http response 200 and then when in my php script I print the post parameters and file names I get the correct values but together with some junk bytes. Here is the body of my http post:

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--"
);

Here is the output from the server(ignore [0.0] - it comes from the console where I print the result)

[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

And the php script on the server which is as simple as you can think of:

<?php 
    print_r($_POST) ;
?>

Solution

  • 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
    );
    

    ...I would say is the way it should be done