【发布时间】:2017-05-09 15:33:51
【问题描述】:
当我通过 POST 请求向服务器发送 JSON 对象时,服务器返回错误消息。
代码:
public String sendStuff(String reqUrl,String arg1, String arg2){
String response;
try{
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("argument1",arg1);
jsonObject.accumulate("argument2",arg2);
String json = jsonObject.toString();
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
out.writeBytes(URLEncoder.encode(json,"UTF-8"));
out.flush();
out.close();
int HttpResult = conn.getResponseCode();
if(HttpResult == HttpURLConnection.HTTP_OK){
response = convertStreamToString(conn.getInputStream());
return response;
}
}catch (Exception e) {
e.printStackTrace();
}
return null;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
错误信息:
{"ERROR":"JSONObject 文本必须在 1 [字符 2 第 1 行] 处以 '{' 开头"}
根据 RESTful 服务,只有当 JSON 格式错误时才会返回此错误消息。我已经通过 Chrome 扩展程序手动测试了该服务,它可以正常工作。
我认为应该不会有错误,因为我是通过 org.json 包中的方法直接将 JSON 转换为字符串。
我搜索了解决方案,但找不到。
【问题讨论】:
标签: java android json rest post