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

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

Related

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");

Sending POST json from Android and receiving on Django

I am trying to get an android app to interact with a server in Django.
The app is trying to POST "json" data to Django. However, I am unable to receive the object on the Django end.
The value of request.POST is <QueryDict: {}> although the data sent isn't blank. Following is the code snippet for POST request from android.
public static String POST(String url,JSONObject obj){
InputStream inputStream = null;
String result = "";
try{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
String json = obj.toString();
StringEntity se = new StringEntity(json);
httpPost.setEntity(se);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type","application/json");
HttpResponse httpResponse = httpClient.execute((HttpUriRequest)httpPost);
inputStream = httpResponse.getEntity().getContent();
if(inputStream!=null){
result = convertInputStreamToString(inputStream);
}else{
result = "Did not work!";
}
}catch(Exception e){
}
return result;
}
EDIT:
Earlier, I was getting CSRF error and handled it this way (I haven't worked with Django enough to know if this is correct way to handle CSRF error)
#csrf_exempt
def search(request):
logger.debug(request.POST)
"""Code for JSON object processing"""
Any help with rectifying the problem would be highly appreciated.
OK I'm not very fluent in java but it seems to me that your request is well formed.
I think the issue is that you are sending the data as a json string instead of as if it was a raw form. When you do it this way, the data is not displayed in request.POST but in request.body as what it is: a json string, not form-like data.
So I think you have to take one of these ways:
send the data from the Android app as a form (not json-like). This way you'll see it in request.POST or
translate request.body into a dict and work with it instead of request.POST
Hope this helps! :)

How can i convert the string with special characters into json object

Hi i am trying to parse the string and convert it in to JSONObject.But it is not converted and giving the error like
"07-28 11:36:47.674: WARN/System.err(6050): org.json.JSONException: Unterminated string at character 3136 of {"data":[{""...."(there is my data)
First i thought there is some special characters like ~,#,%,& and replace the characters with " " but there is no result and giving the same error.
And i modified the web services data by encoding with UTF-8 format. and i used the code to get decode the UTF-8 formatted data in my application.here is my code:
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, "UTF-8");
params.setBooleanParameter("http.protocol.expect-continue",false);
HttpClient httpclient = new DefaultHttpClient(params);
HttpGet httpget =new htpGet("http://www.mylink.com"+todaydate);
try
{
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
jsonText = EntityUtils.toString(entity, HTTP.UTF_8);
Log.d("TEST", jsonText); /this is the result string
}
catch (Exception e)
{
}
JSONObject jObj = new JSONObject(jsonText.toString());
Here i cannot convert the string(jsonText) into json object(jobj).But in logcat it is displaying the string jsonText perfectly. Is there any suggestion to get the data as json object.
I need to use the Json object in my application.
If you are certain that the JSON data is valid and no special characters are causing problems then "Unterminated string at character" could mean that you have not received the whole string.
You could prove this by checking a substring from the end and displaying that in logcat
If not then you need to start looking for the special characters again

Special characters pose problems with REST webservice communication

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.

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