Ok I really find it very strange , I will paste code if someone can help me. To make it clear I do a POST request in Android and back-end server is in node.js.In node.js I get the following exception SyntaxError: Unexpected token in JSON at position 144
and in Android 400 bad request
(URL is good). I send JSON data to the server, the problem is that node can't parse the JSON I send to it.
protected JSONObject doInBackground(String... params) {
JSONObject postData = new JSONObject();
UserData user = UserData.loadData(CheckOut.this);
SaveComand sc = SaveComand.loadData();
double pretTotal = 0;
String food ="";
for(Product pr : sc.products){
pretTotal += pr.getPret();
food += pr.getNume()+",";
}
food = new String(food.substring(0,food.length()-1));
HttpURLConnection conn = null;
try {
URL url = new URL(params[0]);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.connect();
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
postData.put("username", user.user.getNume());
postData.put("nume", nume.getText().toString());
postData.put("idRest", sc.products.get(0).getRestId());
postData.put("adresa", adresa.getText().toString());
postData.put("phone", phone.getText().toString());
//postData.put("food", food);
postData.put("pretTotal", pretTotal);
Log.d("STATE", postData.toString());
wr.writeBytes(postData.toString());
wr.flush();
wr.close();
StringBuilder response = new StringBuilder();
int status = conn.getResponseCode();
Log.d("STATE",conn.getResponseMessage());
if (status != 200) {
throw new IOException("POST failed with error code " + status);
} else {
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
}
return new JSONObject(new String(response));
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();
}
}
return null;
}
Food
string is equal to strings from an object stored in external storage of device.
So postData
is my JSON object I send to server. If I comment the following line postData.put("food",food);
everything works fine. If I not comment that line I have the above error.
Here is how JSONObject look like: {"username":"gabrill","nume":"asdass","idRest":1,"adresa":"Strada Câmpului 10, Ulmeni 437355, Romania","phone":"0749162780","food":"Mic Dejun Meșteșugar","pretTotal":16.2}
this is the string I pass to server to trigger the error . I really see nothing wrong with food
string.
EDIT Seems like it doesn't like specific special characters
It has nothing to ă
but it doesn't like ș
. What should I do? Replace all special ș chars in database with s?