Put request parameters not getting set - java

This may be standard stuff but unable to get it wokring.
I'm using org.apache.commons.httpclient.methods for making Http request from my Java code. In one instance I've to make a PUT request and pass some parameters. I'm doing it the following way:
PutMethod putMethod = new PutMethod(url);
putMethod.getParams().setParameter("param1", "param1Value");
putMethod.getParams().setParameter("param2", "param2Value");
httpClient.executeMethod(putMethod);
But at the server, when it tries to read these parameters - it can only get null.
However, When I modify my url as url?param1=param1Value&param2=param2Value it works.
How do I get it working using setParameter method?

To add Query Params to PutMethod, follow this method.
NameValuePair[] putParameters = new NameValuePair[2];
putParameters[0] = new NameValuePair(Param1, value1);
putParameters[1] = new NameValuePair(Param2, value2);
HttpClient client = new HttpClient();
PutMethod putMethod = new PutMethod(url);
putMethod.setQueryString(putParameters);
Then Call,
int response = client.executeMethod(putMethod);
Instead of putMethod.setQueryString(putParameters); you could also use
putMethod.setRequestBody(EncodingUtil.formUrlEncode(putParameters, "UTF-8"));
(This is deprecated)
GetMethod, PostMethod have slight differences when adding Query Params compared to the above code.
For More Code Examples : http://www.massapi.com/class/pu/PutMethod.html
Hope this helps.

your server side code has to support the PUT method
for example if its a Servlet you can include the method
doPUT(); // your put request will be delivered to this method
if you use REST based frameworks such as jersey
you can use
#PUT
Response yourPutMethod(){..}

Related

In Java "&curren" is encoded to "¤". How to prevent this

From Java code I want to call a webservice like this:
"http://example.com/mytarget?firstParam=xxx&currency=EUR"
But no matter what I do. As soon as I compose a String with "&currency=" in it, it gets replaced by "¤cy=" instantly, which the webservice doesn't like and responds with an error.
To illustrate, here is a small code snipet I use:
String uri = "http://example.com?test=1&currency=EUR";
HttpGet request = new HttpGet(uri); //string got replaced already!
request.addHeader("content-type", "application/json");
HttpResponse result = httpClient.execute(request);
String json = EntityUtils.toString(result.getEntity(), "UTF-8");
The above code makes a call to:"http://example.com?test=1¤cy=EUR"
Similar Question, no answer:
https://stackoverflow.com/questions/29890388/how-to-get-curren-to-display-literally-not-as-an-html-entity-in-Java
Any ideas?
Or is there a "proper" way to call a webservice from Java code that avoids this problem?

How to extract parameters from a URL regardless the way it written by?

I want a java way to extract the parameters of a URL regardless the way these parameters are written in it, in the regular way like( https://www.facebook.com/Doly.mohamed.Smile9?ref=stream&hc_location=stream ) it's so easy because all i have to do is :
URL url = new URL("www.blabla....etc");
String query = url.getQuery();
try{
String [] params = query.split("&");
for(int i= 0 ; i < params.length; i++){
String [] split = params[i].split("=");
parameters.put(split[0], split[1]);
}
}catch(NullPointerException ex){}
so the parameters values would be :
key = ref value = stream , key = hc_location value = stream
but what shall i do if the URL has parameters written in another way or if the URL does't has it's parameters written in it like in the case of the doPost() way.
and is there is a way to get the extraPathInfo from a URL without using servlets?
You could do that easily with Apache's HTTP utils.
URIBuilder uriBuilder = new URIBuilder(uriString);
List<NameValuePair> urlParameters = uriBuilder.getQueryParams();
String uriWithoutParameters = uriBuilder.clearParameters().toString();
Now you could, for example, easily convert the GET request to a POST request, using other classes from the http utils API.
There is a difference between GET and POST urls
In GET url, parameters are part of URL and in POST they are part of Request-body.
So in POST, the URL may or may not contain the request params, and unless you don't have them in the URL its not possible to extract.
The POST request method is designed to request that a web server
accept the data enclosed in the request message's body for storage.1
It is often used when uploading a file or submitting a completed web
form.
So unless you have the POST request's body. Its difficult to extract the Parameter.
Typically you need HTTP request parameters on HTTP server side. Java HTTP server will parse the request and pass it as ServletRequest object to Servlet.service method. ServletRequest has methods to access the request parameters.

Perform HTTP DELETE with api address and json data using java

I know that to send a POST request to the web I can use this syntax:
HttpPost post = new HttpPost(api_address);
String response = null;
int status_code = -1;
StringEntity se = new StringEntity(json_data, HTTP.UTF_8);
se.setContentType("application/json");
// Set entity
post.setEntity(se);
However, the setEntity methos does not exist for DELETE. So what are the alternatives to send a DELETE with data?
I gave a look to this: HttpDelete with body
but I didnt understand it really... I'm just a beginner!
You can use the solution provided in HttpDelete with body like this:
HttpDeleteWithBody delete = new HttpDeleteWithBody(api_address);
StringEntity se = new StringEntity(json_data, HTTP.UTF_8);
se.setContentType("application/json");
delete.setEntity(se);
This works for me.
But the code listed in
HttpDelete with body
is using annotation library so removed below portion if you do not wanted to include annotation jars else it is ok.
Import: import org.apache.http.annotation.NotThreadSafe;
Annotation above the class:#NotThreadSafe
and place the class in the application and use it according to "fiddler's" comment.
I am sure you can have result.As i am getting success.

How to send a POST request with parameters to an endpoint via JBoss HttpRouter?

I'm working on an ESB project and I need to call a REST service using a POST request. HttpRouter seems to be the right way to do it since it supports both GET and POST methods but I can't find a way to inject parameters inside my call.
How can I do that ?
You can try Apache HTTP library. It's very easy to use and have comprehensive set of class needed to manipulate HTTP request.
Found the answer... It was pretty dumb. All you need to do is to inject parameters inside the Message object and they will be in the body of the request. Here is a sample code created by JBoss and found from a unit test of HttpRouter :
final ConfigTree tree = new ConfigTree("WrappedMessage");
tree.setAttribute("endpointUrl", "http://127.0.0.1:8080/esb-echo");
tree.setAttribute("method", "post");
tree.setAttribute("unwrap", "false");
tree.setAttribute("MappedHeaderList", "SOAPAction, Content-Type, Accept, If-Modified-Since");
HttpRouter router = new HttpRouter(tree);
Message message = MessageFactory.getInstance().getMessage(type);
message.getBody().add("bar");
Message response = router.process(message);
String responseBody = (String)response.getBody().get();
String responseStr = null;
if (deserialize)
responseStr = Encoding.decodeToObject(responseBody).toString();
else
responseStr = responseBody;
return responseStr;

Wrapper class for HttpGet / Post in Java?

Sorry, I'm quite new to Java.
I've stumbled across HttpGet and HttpPost which seem to be perfect for my needs, but a little long winded. I have written a rather bad wrapper class, but does anyone know of where to get a better one?
Ideally, I'd be able to do
String response = fetchContent("http://url/", postdata);
where postdata is optional.
Thanks!
HttpClient sounds like what you want. You certainly can't do stuff like the above in one line, but it's a fully-fledged HTTP library that wraps up Get/Post requests (and the rest).
I would consider using the HttpClient library. From their documentation, you can generate a POST like this:
PostMethod post = new PostMethod("http://jakarata.apache.org/");
NameValuePair[] data = {
new NameValuePair("user", "joe"),
new NameValuePair("password", "bloggs")
};
post.setRequestBody(data);
// execute method and handle any error responses.
...
InputStream in = post.getResponseBodyAsStream();
// handle response.
There are a number of advanced options for configuring the client should you eventually required those.

Categories