Skip to Main Content

Java EE (Java Enterprise Edition) General Discussion

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Create post request with apache HttpClient

843842Jul 5 2008 — edited Jul 12 2008
Hi all
I'm using HttpClient to create a post request. I send this req to a website but the reply isn't as expected.
My request needs to be formatted like this simple request:
POST /abc/index.aspx HTTP/1.1
Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-ms-application, application/vnd.ms-xpsdocument, application/xaml+xml, application/x-ms-xbap, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-shockwave-flash, */*
Accept-Language: en-US
Content-Type: application/x-www-form-urlencoded
UA-CPU: x86
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.0.04506; InfoPath.2)
Host: www.123.com
Content-Length: 32
Connection: Keep-Alive
Cache-Control: no-cache
name=Marcus&surname=Oiiuo&age=11
This is the req generated by Internet Explorer and I need to replicate it programmatically with HttpClient.
I'm using something like
HttpClient client = new HttpClient();
PostMethod httpPostMethod = new PostMethod("http://www.123.com/abc/index.aspx");
NameValuePair[] parameters = {
   new NameValuePair("name", "Marcus"),
   new NameValuePair("surname", "Oiiuo"),
   new NameValuePair("age", "11")
};
httpPostMethod.setRequestBody(parameters);
 
...
httpPostMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
...
client.executeMethod(httpPostMethod);
..
byte[] responseBody = httpPostMethod.getResponseBody();
...
but the response from the server is not ok. The page returned from the server is an error page, it seems that maybe something is missing in the Post headers.
Printing the requestEntity request gives me the post request body and this is ok!
So maybe it's only a header problem.
I know that the 2 important headers are Content-Type and Content-Length, I have check them and they are ok.
The Content-Length is correctly set directly by the httpPostMethod.setRequestBody(parameters); and it returns the correct int body size value.
So I'm trying to set something like
httpPostMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
but the reply is always the error page.
Someone knows how to configure a correct Post request with HttpClient based on these param?
Thanks :)
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Aug 9 2008
Added on Jul 5 2008
2 comments
463 views