Special characters pose problems with REST webservice communication - android

I am trying to post a JSON-object to a REST webservice from an Android application. Everything works fine until I add special characters like å, ä, ö.
JSONObject absenceObject = new JSONObject();
absenceObject.put(INFO_DESCRIPTION, "åka pendeltåg");
StringEntity entity = new StringEntity(absenceObject.toString());
httpPost.setEntity(entity);
httpPost.setHeader("Accept", "application/json";character);
httpPost.setHeader("Content-type", "application/json;charset=UTF-8");
HttpResponse response = httpclient.execute(httpPost);
If I print absenceObject.toString() and copy the result in to a regular rest client it works fine as well.

Try specifying the desired charset in the StringEntity constructor:
StringEntity entity = new StringEntity(absenceObject.toString(), "UTF-8");

If you control both ends of the pipe, you can encode the REST text as shown here Encoding/decoding REST path parameters

Re: Mark's response
Try specifying the desired charset in the StringEntity constructor:
StringEntity entity = new StringEntity(absenceObject.toString(), "UTF-8");
Note that setting charset after the constructor didn't work for me i.e.
entity.setContentEncoding("UTF-8");
I had to do as Mark said and set it in the constructor.
Michael

byte[] buf = body.getBytes(HTTP.UTF_8);
wr.write(buf, 0, buf.length);
Try this it will work.

Related

Send character with UTF-8 from Android app to server side

I have some services with the following header and I want to call these methods in Android application. I wrote the following code for calling service is correct but if I add charset=utf-8 to the header, I get 400 error code. I should send Persian character in some methods and without UTF-8, I get incorrect characters on the server-side. Anyway, Please send your suggestion to edit my code.
Another note: I work with PostMan and post Persian character to the service and it shows correct characters.
WCF Header method:
OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest,
UriTemplate = "Test")]
Android Code:
this.jsonStringer=params[0].toString();
HttpPost request = new HttpPost(uri);
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
StringEntity msg = new StringEntity(jsonStringer);
msg.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
msg.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
request.setEntity(msg);
response = httpClient.execute(request);
When I add request.setHeader("Content-type", "application/json; charset=utf-8"); I get 400 error code!
Header parameters are by default UTF8 but if you are trying to pass your parameters by putting them in the Body, you should do as follow.
Assume you have stored your non utf8 string in value1. First convert your string to utf8 using URLEncoder then add it to your jsonObject and cast it as body.
Here it is a sample code but in Kotlin!
val jsonObject = JSONObject()
jsonObject.put(“param1”,val1)
val val1 = URLEncoder.encode(value1,”utf8”)
jsonObject.put(“param2”,val2) // and so on
val body = jsonObject.toString().toRequestBody(“application/json; charset=utf-8”.toMediaTypeOrNull())
Important Notice
Make sure you string is not urf8 because unless you are reading it from an ANSI txt file, they are Unicode and you do not need to convert them. If you don’t see the result as you should see on the server, that is another issue.
This may be caused by the difference between the header you set in the request and the header you set in the basicheader.You can set their content-type to the same format.This setting in Java can solve this problem,you can try it in your program.
public static void main(String args[]) throws ClientProtocolException, IOException {
String json="{\"user\":{\"Email\":\"123\",\"Name\":\"sdd\",\"Password\":\"sad\"}}";
CloseableHttpClient httpClient=HttpClientBuilder.create().build();
HttpPost request = new HttpPost("http://localhost:8012/ServiceModelSamples/service/web/user");
request.setHeader("Accept", "application/json");
request.setHeader("Content-Type", "application/json;charset=utf-8");
StringEntity msg = new StringEntity(json);
msg.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json;charset=utf-8"));
msg.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
request.setEntity(msg);
HttpResponse response = httpClient.execute(request);
System.out.println(response);
}

Problems to send data with spanish chars from android app but not from postman to a restful web service

I have a web service RESTful that it saves to a data base. I pass data with JSON.
If i pass a JSON from POSTMAN, all is ok. If i pass the data (JSON) from an android app, the server can not save to the data base IF THERE ARE SPANISH chars like "ó, ñ, etc.".
Why from postman yes and from android app not?.
I try adding ISO-8859-1 but it doesn't work. Where is the error? Sql server?, android app?, IIS?. If the data doesn't contain spanish chars, all is fine, with spanish chars, it doesn't work.
The code in the android app is like:
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost;
httpPost = new HttpPost("http://"...
httpPost.setHeader("content-type", "application/json" );
httpPost.setHeader("charset", "ISO-8859-1");
JSONObject jSONObject = new JSONObject();
try
{
jSONObject.put("Mensaje", params[0].mensaje);
jSONObject.put("IdUsuarioOrigen", params[0].idUsuarioOrigen);
jSONObject.put("IdUsuarioDestino", params[0].idUsuarioDestino);
StringEntity stringEntity = new StringEntity(jSONObject.toString());
stringEntity.setContentType("application/json");
stringEntity.setContentEncoding("ISO-8859-1");
httpPost.setEntity(stringEntity);
HttpResponse httpResponse = httpClient.execute(httpPost);
strHttpResponse = EntityUtils.toString(httpResponse.getEntity());
EDIT::::::::::::::::::::::::::::::::::::
I'm debugging for some days. The point is this:
The code in android app is:
...
httpPost.setHeader("content-type", "application/json" );
httpPost.setHeader("charset", "ISO-8859-9");
JSONObject jSONObject = new JSONObject();
try
{
jSONObject.put("Mensaje", params[0].mensaje);
jSONObject.put("IdUsuarioOrigen", params[0].idUsuarioOrigen);
jSONObject.put("IdUsuarioDestino",
params[0].idUsuarioDestino);
StringEntity stringEntity = new
StringEntity(jSONObject.toString());
stringEntity.setContentType("application/json");
stringEntity.setContentEncoding("ISO-8859-9");
httpPost.setEntity(stringEntity);
HttpResponse httpResponse = httpClient.execute(httpPost);
strHttpResponse =
EntityUtils.toString(httpResponse.getEntity());
And if i debug httpPost before "httpClient.execute(httpPost);" the httpPost is ok, has the data inside (ó, ñ etc.) but when it arrives to the c# back-end, "mensaje" is null:
public HttpResponseMessage PostMensaje(Mensajeria mensaje)
{
if (mensaje == null)
return
Request.CreateResponse(HttpStatusCode.InternalServerError, "El mensaje no
puede llegar al servidor");
But if httpPost in android app doesn't have any spanish characters, all is well and in the back-end "Mensajeria mensaje" "mensaje" is not null.
Why is null only for to carry spanish characters?.
With postman, all is well, with or without spanish chars.
I must yo say, my last attempt was to add web.config in web services .net:
<globalization
fileEncoding="ISO-8859-9"
requestEncoding="ISO-8859-9"
responseEncoding="ISO-8859-9"
/>
But the json when it reaches to the web service, "mensaje" is null (but it came out well of the android code). If JSON came out with "ó, ñ etc. "mensaje" in .net is null, otherwise, everything is perfect.
public HttpResponseMessage PostMensaje(Mensajeria mensaje)
{
try this:
httpPost.setHeader("content-type", "application/json;charset=utf-8" );
and
strHttpResponse = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");

How receive JSON object via HttpClient?

I use HttpClient in android to send post request:
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost(hostNameCollection);
StringEntity se = new StringEntity(jsonObj.toString());
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
request.setEntity(se);
HttpResponse response = client.execute(request);
Log.v("HttpLogClient.logJSONObject", "wyslano JSON");
and I'dont know how I can receive JSON object on my Java EE servlet.
you need to read the response body text, then parse as JSON,
String result = EntityUtils.toString(response.getEntity());
JSONObject jo = new JSONObject(result);
read the body of the http post ( server-side ) by getting the a stream object on the body and then reading it.
Once youve read it , convert the bytes to chars and that will be json which you can use to build a json object like a jsonNode using 'jackson' libs.
If you are using plain servlets the json stream is located in the body of the HttpServletRequest : request.getReader() or request.getInputStream();
To make things easier you could use a library handling databinding for you.
Have a look at Genson http://code.google.com/p/genson/.
YouClass object = new Genson().deserialize(request.getReader(), YourClass.class);
// or to a plain map
Map<String, Object> map = genson.deserialize(request.getReader(), Map.class);

Android: How to set encoding in JSONStringer for webservice requests?

I finished the English version of my application and I am currently working on my Arabic application version. Although my English webservices were working fine, there seems to be a problem with my Arabic webservices, I feel that I need to specify the encoding type (utf-8) when I construct my JSON request using the JSONStringer class. Is there a way to do that?
Here is an example of a method that constructs my JSON request,
public static String initLoginJSONRequest(String username, String password){
String parentString = null;
String childString = null;
try{
childString = new JSONStringer()
.object()
.key("username").value(username)
.key("password").value(password)
.endObject()
.toString();
parentString = new JSONStringer()
.object()
.key("UserCredentials").value(childString)
.endObject()
.toString();
}catch(JSONException e){
e.printStackTrace();
}
return parentString;
}
EDIT
I would also like to add that I specify that my encoding is utf-8 in my HttpPost as shown below,
HttpPost post = new HttpPost(getUrl);
StringEntity se = new StringEntity(jsonString);
se.setContentType("application/json;charset=UTF-8");//text/plain;charset=UTF-8
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json;charset=UTF-8"));
post.setEntity(se);
response = client.execute(post);
But it is not recieving my Arabic charecters on the webservice end (written in .NET) correctly.
Try to change UTF-8 by ISO-8859-1
The answers here can help you:
Android - Read an XML file with HTTP GET

How to send unicode characters in an HttpPost on Android

I'm trying to allow multilingual support in my app which makes an HTTP post to upload new messages. What do I need to do in order to support japanese & other non latin based languages? my code currently looks something like this:
//note the msg string is a JSON message by the time it gets here...
private String doHttpPost(String url, String msg)
throws Exception {
HttpPost post = new HttpPost(url);
StringEntity stringEntity = new StringEntity(msg);
post.setEntity(stringEntity);
return execute(post);
}
Try setting encoding on StringEntity:
StringEntity stringEntity = new StringEntity(msg, "UTF-8");

Categories

Resources