好吧,我真的觉得很奇怪,如果有人可以帮助我,我会粘贴代码。为了清楚起见,我在Android中执行POST请求,后端服务器在node.js中。在node.js中,我得到以下异常SyntaxError: Unexpected token in JSON at position 144
和Android 400 bad request
(URL很好)。我将JSON数据发送到服务器,问题是节点无法解析我发送给它的JSON。
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
字符串等于来自设备外部存储中存储的对象的字符串。
因此postData
是我发送到服务器的JSON对象。如果我在下面的行postData.put("food",food);
中添加注释,则一切正常。如果我不对此行发表评论,则会出现上述错误。
JSONObject如下所示:{"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}
这是我传递给服务器以触发错误的字符串。我真的没有发现food
字符串有问题。
编辑似乎不喜欢特定的特殊字符
ă
不需要任何内容,但不喜欢ș
。我该怎么办?将数据库中的所有特殊all字符替换为s?
答案 0 :(得分:0)