をしながら、サーバがエラーメッセージを返します。不正なJSON私はPOSTリクエストを介してサーバにJSONオブジェクトを送信するときにPOSTコール
コード:
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
私の問題は解決しません。 –