Perform HTTP DELETE with api address and json data using java - 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.

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?

StringEntity object from JSONObject gives java.io.UnsupportedEncodingException

I am new to Java and trying to make native android application which includes making HTTP Calls to API Server. Now My issue is that for making HTTP POST (apache httpPost and httpClient) call with some JSON data. So to make StringEntity out of JSONObject I am writing this line of code:
StringEntity userDataStringEntity = new StringEntity(userDataString);
Where StringEntity is imported from import org.apache.http.entity.StringEntity;.
I have tried searching for this issue and I am finding same method with same "string" parameter.
Here are some links, but it didn't help me:
How to send a JSON object over HttpClient Request with Android?
How to send a JSON object over Request with Android?
That's definitely weird, by default the StringEntity goes for the charset "ISO-8859-1" which tells me that the userDataString is in another charset.
Either way, try:
StringEntity userDataStringEntity = new StringEntity(userDataString, "UTF-8");
This will work for utf-8 encoded strings.
Perhaps unrelated, but I was getting an error at compile time, as the new StringEntity(str) wasn't wrapped in a try catch.
Might be of use to someone tho :)

UrlEncodedFormEntity doesn't encode underscore

I want to use a remote API from my Android device, but for some reason, the UrlEncodedFormEntity class doesn't transform the _ with %5f like the remote API seems to expect. As a consequence, using this code:
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(
new BasicNameValuePair("json",
"{\"params\":{\"player_name\":\"Toto\",
\"password\":\"clearPass\"},
\"class_name\":\"ApiMasterAuthentication\",
\"method_name\":\"login\"}")
);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
ResponseHandler responseHandler = new BasicResponseHandler();
httpClient.execute(httpPost, responseHandler);
send a post request to the server, with this content:
json=%7B%22params%22%3A%7B%22player_name%22%3A%22Toto%22%2C%22password%22%3A%22clearPass%22%7D%2C%22class_name%22%3A%22ApiMasterAuthentication%22%2C%22method_name%22%3A%22login%22%7D
I would like it to be like this (replacing the preivous underscore by %5F):
json=%7B%22params%22%3A%7B%22player%5Fname%22%3A%22Toto%22%2C%22password%22%3A%22clearPass%22%7D%2C%22class%5Fname%22%3A%22ApiMasterAuthentication%22%2C%22method%5Fname%22%3A%22login%22%7D
I don't have control over the API, and the official client of the API behave like this. It seems to be the expected behaviour for an URL normalization
Am I missing something? I first thought it was an UTF-8 encoding issue, but adding HTTP.UTF-8 in the constructor of UrlEncodedFormEntity doesn't solve the problem.
Thanks for your help.
EDIT: Finally, the problem didn't come from this unescape underscore. Even if the other client I tried to reproduce the behaviour escaped it, I only had to set the proper header:
httpPost.addHeader("Content-Type","application/x-www-form-urlencoded");
And the request worked just fine. Thanks everyone, and especially singh.jagmohan for his help (even if the problem was finally elsewhere)!
"_" isn't a reserved symbol for urls.
setting : Content-Type: application/x-www-form-urlencoded'
should solve the problem. Otherwise you can try replacing it, if you really need this option:
String.Replace("_", "%5f");
See percent encodeing , replace
You can try the following code, it works for me.
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(serviceUrl);
MultipartEntity multipartEntity = new MultipartEntity();
// Also, in place of building JSON string as below, you can build a **JSONObject**
// and then use jsonObject.toString() while building the **StringBody** object
String requestJsonStr = "{\"params\":{\"player_name\":\"Toto\",\"password\":\"clearPass\"},\"class_name\":\"ApiMasterAuthentication\",\"method_name\":\"login\"}";
multipartEntity.addPart("json", new StringBody(requestJsonStr));
httpPost.setEntity(multipartEntity);
HttpResponse response = httpClient.execute(httpPost);
} catch (Exception ex) {
// add specific exception catch block above
// I have used this one just for code snippet
}
PS: The code snippet requires two jar files apache-mime4j-0.6.jar and httpmime-4.0.1.jar.
Hope this helps.

Put request parameters not getting set

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(){..}

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