PostMethod: How to make request to a given address?
-
19-09-2019 - |
Question
I would like to reate a POST request to a given address, let it for example be
for POST requests I've created an universal method:
private String postMethod(String url, HashMap<String, String> headers, String encodedAuthorizationString) throws HttpException, IOException {
HttpClient client = new HttpClient();
PostMethod post = new PostMethod(url);
post.setRequestHeader("Authorization", encodedAuthorizationString);
if(headers != null && !headers.isEmpty()){
for(Entry<String, String> entry : headers.entrySet()){
post.setRequestHeader(new Header(entry.getKey(), entry.getValue()));
}
}
client.executeMethod(post);
String responseFromPost = post.getResponseBodyAsString();
post.releaseConnection();
return responseFromPost;
}
where headers represents pairs (key, value), for example ("product[title]", "TitleTest"). I tried to use the method by calling postMethod("http://staging.myproject.com.products.xml", headers, "xxx"); where headers included pairs
("product[title]", "TitleTest"),
("product[content]", "TestContent"),
(product[price], "12.3"),
("tags", "aaa,bbb")
but the server returned an error message.
Does anyone know how to parse the address
in order to use it with the method above? Which part is url? Are parameters set correctly?
Thank you.
Solution
I've found a problem:
private String postMethod(String url, HashMap<String, String> headers, String encodedAuthorizationString) throws HttpException, IOException {
HttpClient client = new HttpClient();
PostMethod post = new PostMethod(url);
post.setRequestHeader("Authorization", encodedAuthorizationString);
if(headers != null && !headers.isEmpty()){
for(Entry<String, String> entry : headers.entrySet()){
//post.setRequestHeader(new Header(entry.getKey(), entry.getValue()));
//in the old code parameters were set as headers (the line above is replaced with the line below)
post.addParameter(new Header(entry.getKey(), entry.getValue()));
}
}
client.executeMethod(post);
String responseFromPost = post.getResponseBodyAsString();
post.releaseConnection();
return responseFromPost;
}
parameters:
("product[title]", "TitleTest"),
("product[content]", "TestContent"), (product[price], "12.3"), ("tags", "aaa,bbb")
OTHER TIPS
You seem to be confusing URL query parameters, such as product[price]=12.3 with HTTP request headers. Using setRequestHeader() is meant to set the HTTP request headers, which are meta-data associated with any HTTP request.
In order to set the query parameters, you should append them to the url, after a '?' and UrlEncoded, as in your example url.