2016-12-24 8 views
0

をしながら、サーバがエラーメッセージを返します。不正な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に変換していますので、エラーがあってはならないと思います。

私は解決策を探しますが、ものを見つけることができませんでした。

答えて

0

あなたはjson.toString()から返さString内のデータをURLEncodeをする必要はありません。 String自体をUTF-8でエンコードされたバイトストリームとしてストリーミングできなければなりません。オブジェクトのURLエンコードでは、 '{'などの特殊なJSON端末文字をパーセント記号で表現された同等のもの(%7Bなど)に変換しますが、これはHTTPリクエストの本文には不適切です。考慮すべき

もう一つは、あなたが本当にこの種のもののためにDataOutputStreamを必要としないことである - DataOuputStreamは、Javaのプリミティブオブジェクトを変換するものであるのに対し、出力はUTF-8エンコードされたJSON文書を表すバイトのストリームすることになっていますバイトストリームに変換します。あなたはすでにバイトストリームを持っているので、OutputStreamに送信するだけです。

final String json = jsonObject.toString(); 
    final OutputStream out = new conn.getOutputStream(); 
    out.write(json.getBytes("UTF-8")); 
    out.flush(); 
    out.close(); 
0

はヘッダを付加して、これを試してみてください:

conn.setRequestProperty("Accept", "application/json"); 
conn.setRequestProperty("Content-Type", "application/json"); 
+0

でも同じエラーが表示されます。 –

+0

私はそれがうまくいくと思います。それ以外の場合は、conn.setRequestProperty( "Accept"、 "application/json; charset = utf-8");を試してください。 conn.setRequestProperty( "Content-Type"、 "application/json; charset = utf-8"); – SujitKumar

+0

私の問題は解決しません。 –

関連する問題