當我通過POST請求將JSON對象發送到服務器時,服務器返回錯誤消息。進行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轉換爲字符串。
我搜索了一個解決方案,但找不到一個解決方案。
仍然給出了同樣的錯誤。 –
我認爲它應該工作。否則請嘗試> conn.setRequestProperty(「Accept」,「application/json; charset = utf-8」); conn.setRequestProperty(「Content-Type」,「application/json; charset = utf-8」); – SujitKumar
不解決我的問題。 –