Apache Commons HttpClient PostMethod support? - java

I am curios about how one can set the request properties for a PostMethod in Apache Commons HttpClient?
I am refactoring some code written using HttpURLConnection class to post which looks like the following:
conn1.setRequestProperty(
"Content-Type", "multipart/related; type=\"application/xml\"; boundary="
+ boundary);
conn1.setRequestProperty("Authorization", auth);
... ...
To use:
PostMethod method = new PostMethod(_Server);
method.setRequestBody(...); or
method.setRequestHeader(...);
But i am not sure if / how this will map to what i want to do with the original URL class... can anyone help clarify how to set request properties with PostMethod class?
Thanks a lot!
-alex

Those are both request headers, so you would need to call setRequestHeader() to establish those values on the connection. HttpClient also supports handling basic authentication so the "Authorization" header can be refactored out, depending on how deep your changes go.

Related

android HTTP POST fail

I'm trying to connect and post to a simple java webservice, running the post's URL from chrome succeeded, but android code skip the following lines (without throwing errors), but the webservice doesn't accept the post
HttpPost post = new HttpPost(setFacebookEventsAddress+userId+"/"+accesstoken);
post.setHeader("Accept", "application/json");
post.setHeader("Content-type", "application/json");
HttpResponse response = client.execute(post);
the webservice method signature handling the above request:
#GET
#Path("setData/{user_id}/{accessToken}")
#Produces(MediaType.APPLICATION_JSON+ ";charset=utf-8")
public String setData(#PathParam("user_id") String user_id,
#PathParam("accessToken") String accessToken) {
since I manage to post throw my browser, anyone can help with what's wrong with my android code?
URL url = new URL(setFacebookEventsAddress+userId+"/"+accesstoken);
HttpURLConnection con = (HttpURLConnection) url
.openConnection();
ja = readStream(con.getInputStream());
Using HttpURLConnection instead of HttpPost did the trick for me, thanks for all the helpers!
It is not possible to say with any certainty (given the evidence), but my guess would be that the expression
setFacebookEventsAddress + userId + "/" + accesstoken
is evaluating to a different URL to the one you are using from the web browser.
I suggest that you try the following:
Turn on request logging on your server, and compare the URLs in the requests being sent.
Modify your client to print out the response status code and the response body. The latter is likely to be an error page that will give you more clues.
Another possible problem is that your code doesn't appear to be sending any body with the POST request.
On revisiting this, the problem was that you were using / trying to do a POST to a web service that you had configured to support GET only. I expect that if you had looked at the status code you would have found that the response code was "Method not supported".

Posting to a form based on what HttpGet returns with Apache's HttpClient

I'm posting data to a website form using Apache's HttpClient class. The form is retrieved using the following lines of code:
HttpGet get = new HttpGet(url);
HttpResponse response = client.execute(get);
The website that I'm retrieving the form from requires authentication to access the form. If the request isn't authenticated, the website redirects the request to a login form page that will subsequently redirect back to the original page on successful authentication.
I want to cleanly detect whether or not the GET request returns the login page or the desired form page so that I can either POST login data or form data. The only way I can think of to do this is by reading from the content InputStream of the entity of the response and parsing each line. But that seems somewhat convoluted. I haven't worked with the Apache HttpComponents api before so I'm not sure if this would be the only and best way to accomplish what I want to accomplish.
EDIT: To clarify question, I'm asking if there is a set way to handle forms with Apache's HttpClient. I somewhat know how to achieve what I'm looking to do, but it looks very ugly and I'm hoping there is an easier and faster way to achieve it. For example, if there was some way to do the following:
HttpGet get = new HttpGet(url);
HttpResponse response = client.execute(get);
if(parseElements(response.getEntity()).hasFormWithId("login")) {
// post authentication data
} else {
// post actual form data
}
Because of my inexperience with Apache's HttpClient api, I'm not sure if what I'm looking for in the API is too abstract for the intent of the API.
You can modify the behavior of the HttpClient by setting the HttpClient Parameters
DefaultHttpClient client = new DefaultHttpClient();
client.setDefaultHttpParams(client.getParams().setBoolean(ClientPNames.HANDLE_REDIRECTS, false));
Which disables handling redirects automatically.
See also:
Automatic redirect handling
HTTP Authentication
DefaultHttpClient API

How to execute HTTP GET method with cookie value filled?

My problem is that I want to use Java to implement an application which sends an HTTP GET request to some website. However, the target website needs one cookie to be set:
Country=US
If this cookie is null it returns bad indications. My question is how I can set the cookie value before I use openConnection()?
You can use URLConnection and add a Cookie header:
http://www.hccp.org/java-net-cookie-how-to.html
URL myUrl = new URL("http://www.yourserver.com/path");
URLConnection urlConn = myUrl.openConnection();
urlConn.setRequestProperty("Cookie", "Country=US");
urlConn.connect();
You can place the cookie your self by adding a header, or use a higher level HTTP library like Apache's HttpClient which API includes cookies handling features.

How to add json to the body of an http post in java

I'm trying to post some JSON data in java for an Android app I'm working on. Is the below valid or do I need to push the JSON string in a different way?
HttpPost httpost = new HttpPost("http://test.localhost");
httpost.setEntity(new StringEntity("{\"filters\":true}"));
httpost.setHeader("Accept", "application/json");
httpost.setHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
//... other java code to execute the apache httpclient
Thank you in advance
You should set the Content-Type header to "application/json". Everything else looks good.

Is Jakarta HttpClient sutitable for the following task?

I try to talk to a server, by telneting to it, and send the following command through telnet terminal :
POST /%5bvUpJYKw4QvGRMBmhATUxRwv4JrU9aDnwNEuangVyy6OuHxi2YiY=%5dImage? HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Content-Length: 164
[SORT]=0,1,0,10,5,0,KL,0&[FIELD]=33,38,51,58,68,88,78,98,99,101,56,57,69,70,71,72,89,90,91,92,59,60,61,62,79,80,81,82&[LIST]=1155.KL,1295.KL,7191.KL,0097.KL,2267.KL
This works very fine. Now, I wish I can use HttpClient, to talk to the server, as I use telnet to talk to the server. The reason I wish to use HttpClient, instead of using raw TCP socket, is because HttpClient does support NTLM.
However, when I use POST method with NameValuePair :
new NameValuePair("[SORT]", "0,1,0,10,5,0,KL,0")
The request will become URL encoded. The server doesn't understand URL encoded request.
%5BSORT%5D: 0%2C1%2C0%2C10%2C5%2C0%2CKL%2C0
Is there any way I can avoid this? If not, what is the alternative library I can use? I wish to support NTLM as well.
As I mentioned in the other thread, this is not even valid HTTP POST. So you can't do it with default post mechanism in HttpClient. You need to make the invalid body yourself and post it.
Assuming you are using HttpClient 3, following code should work,
HttpClient httpClient = new HttpClient();
PostMethod method = new PostMethod(url);
String badFormPost = "[SORT]=0,1,0,10,5,0,KL,0&[FIELD]=33,38,51,58,68,88,78,98,99,101,56,57,69,70,71,72,89,90,91,92,59,60,61,62,79,80,81,82&[LIST]=1155.KL,1295.KL,7191.KL,0097.KL,2267.KL";
RequestEntity entity = new StringRequestEntity(badFormPost,
"application/x-www-form-urlencoded", "UTF-8");
method.setRequestEntity(entity);
method.setContentChunked(false);
httpClient.executeMethod(method);
...
It's getting URL encoded because your request formed with HTTPClient may be a GET request instead of a POST and is missing this header:
Content-Type: application/x-www-form-urlencoded
Look for the HTTPClient setting to set the Content-Type header correctly and make sure your request is a POST, not a get and you should be golden.

Categories