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");
Related
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");
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! :)
It has been a while since I programmed for Android and I have lost all my previous work which had the code in it I am having problems with. I am developing an app for both Android and iPhone which connect to the same server to download data. All is well in the iPhone version but on Android when I hit the server with the post data containing the method name I would like to to run on the server it seems that the data is not added to the request.
Why is the POST not working in this request for Android but does for the iPhone version of the app?
Here is the code I am using:
public static void makeRequest() throws Exception {
Thread t = new Thread() {
public void run() {
Looper.prepare(); //For Preparing Message Pool for the child Thread
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000);
HttpResponse response;
HttpEntity entity;
JSONObject json = new JSONObject();
try {
HttpPost post = new HttpPost("http://divisi.co.uk/rest/requesthandler.php");
json.put("method", "getEventListData");
StringEntity se = new StringEntity(json.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
response = client.execute(post);
entity = response.getEntity();
String retSrc = EntityUtils.toString(entity);
JSONObject result = new JSONObject(retSrc); //Convert String to JSON Object
if(result.getString("SC") == "200"){
JSONArray data = result.getJSONArray("data");
}
else{
}
} catch(Exception e) {
e.printStackTrace();
}
Looper.loop(); //Loop in the message queue
}
};
t.start();
}
The response I get mack from the server is:
{"data":{"scalar":""},"SC":405,"timestamp":1363788265}
Meaning the method name was not found, i.e. not posted in my request to the server.
heres an example of how i do things like this:
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost("http://divisi.co.uk/rest/requesthandler.php");
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart(new FormBodyPart("method", new StringBody("getEventListData")));
reqEntity.addPart(new FormBodyPart("NEED_A_KEY_HERE", new StringBody("" + json.toString())));
postRequest.setEntity(reqEntity);
HttpResponse response = httpClient.execute(postRequest);
JSONObject responseDict = new JSONObject(EntityUtils.toString(response.getEntity()));
allow this is your "http://divisi.co.uk/rest/requesthandler.php" page code, then in android you can use this... you don't allow post in your URL,
use fiddler on your sever side. see if the http message is correct. it seems your sever side problem, can you show us your sever side code which receive and parse json.
If the server can't read your request try to remove:
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
It will use the mime type defaults HTTP.PLAIN_TEXT_TYPE i.e. "text/plain".
I don't see any other possibility, if your code is the one you posted and not a more complicated input JSON object.
Your code to set the POST body may be just fine. I think the problem may be with your web service. Try using something like Rested or curl to manually make the call to your server. I made exactly the same request you are making, including with and without the POST body, and I got the same response from your server:
{"data":{"scalar":""},"SC":405,"timestamp":1365704082}
Some things that may be tripping you up:
JSONObject result = new JSONObject(retSrc); //Convert String to JSON Object
if(result.getString("SC") == "200"){
JSONArray data = result.getJSONArray("data");
}
Here, you are comparing the string "405" to "200" using ==, when you should first do a null check and then use .equals("200") instead. Or, use result.getInt("SC") == 200 since this is an integer type in your response JSON.
Also, the "data" entity from your server response is not actually coming back as a JSON array. You should use getJSONObject("data") instead.
Additionally, it's always a good idea to externalize your strings.
Here's how the code should look:
public static final String JSON_KEY_SC = "SC";
public static final String JSON_KEY_DATA = "data";
...
JSONObject result = new JSONObject(retSrc); //Convert String to JSON Object
String sc = result.getString(JSON_KEY_SC);
if (sc != null && sc.equals("200")) {
JSONObject data = result.getJSONObject(JSON_KEY_DATA);
}
else {
...
}
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
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.