StringEntity object from JSONObject gives java.io.UnsupportedEncodingException - java

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 :)

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?

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.

In Java, using HttpPost (apache commons HttpClient) when sending JSON POST - should I URL encode the body?

I'm sending a RESTful JSON POST request using Apache HttpClient (to a 3rd party API)
Should I URL encode the JSON body?
And if something in the content is already URL encoded (e.g. I send HTML that has some links with URL encoded chars, e.g. #22) should I expect to get the content as is on the other side without it being decoded?
E.g. if i'm doing something like this
String html = "<a href='http://example.com?charOfTheDay=%22'>click me</a>";
// Build the JSON object
JSONObject jsonObj = new JSONObject();
jsonObj.put("html", html);
jsonObj.put("otherKey",otherValue);
//...
// Create the POST object and add the parameters
HttpPost httpPost = new HttpPost(url);
StringEntity entity = new StringEntity(jsonObj.toString(), HTTP.UTF_8);
entity.setContentType("application/json");
httpPost.setEntity(entity);
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(httpPost);
Should I expect getting the same value on the receiving end, after getting the value of the "html" key?
e.g. on the receiving end
//after parsing the request string to a JSON object
String html = inputJsonObject.get("html")
// should return "<a href='http://example.com?charOfTheDay=%22'>click me</a>"
Are there any other steps I need to do to make sure what I send is what is received "as is"?
There's sort of two contexts you have to worry about here:
JSON
You have to make sure that the JSON you generate is valid JSON (duh). This means making sure that all the { } and [ ] syntax is in the right place and making sure that the field values you are inserting into the JSON object are safely escaped (like escaping that HTML snippet in your question --some of the quote characters would need to be escaped). BUT because you're using a standard JSON Java library, you don't have to worry about this...it will take care of all this for you.
HTTP
The JSON string then has to be inserted into the HTTP request body. No escaping needs to be done here--just insert the raw JSON string. HTTP, as a protocol, will accept anything inside the request/response bodies, including raw binary data.
Anyway that was kind of long, but I hope it helped.
The Content-Type in your http header should be application/json, so you oughtn't URL encode the body of the http request.
URL encoding is meant to prevent users from using characters that are special in representing URLs (such as '/').
You don't have to worry about links in the content being decoded either, unless you use a Content-Type in your http header that suggests that the server should decode the body, such as application/x-www-form-urlencoded

Post XML in Java and Get the response code

I need to send XML data to a URL. The XML data is contained in a stringbuffer.
I need to post it and get the response code.
Can anyone tell me how to do it?
I have a piece of code, but eclipse says its deprecated
PostMethod postMethod = new PostMethod(URL);
InputStream stream = new StringBufferInputStream(command);
postMethod.setRequestBody(stream);
Javadoc says to use setRequestEntity(RequestEntity) instead.

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