Skip to content
Advertisement

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.1rn"
        + "Host: myhost.comrn"
        + "User-Agent: sampleAgentrn"
        + "Content-type: multipart/form-data, boundary=AaB03xrn" 
        + "Content-Length: 172rnrn"
        + "--AaB03xrn"
        + "content-disposition: form-data; name="asd"rnrn123rn--AaB03xrn"
        + "content-disposition: form-data; name="pics"; filename="file1.txt"rn"
        + "Content-Type: text/plainrnrn555rn"
        + "--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) ;
?>

Advertisement

Answer

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

StringBuffer str = new StringBuffer();
str.append("POST /tst/query.php HTTP/1.1rn"
         + "Host: myhost.comrn"
         + "User-Agent: sampleAgentrn"
         + "Content-type: multipart/form-data, boundary="" + boundary + ""rn" 
         + "Content-Length: " + body.length() + "rn"
         + "rn"
         + body
);

…I would say is the way it should be done

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement