2016-12-24 97 views
0

當我通過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轉換爲字符串。

我搜索了一個解決方案,但找不到一個解決方案。

回答

0

您不需要進行urlencode從json.toString()返回在String數據。您應該能夠將String本身作爲UTF-8編碼的字節流進行流式傳輸。對該對象進行URL編碼時,會將特殊的JSON終端字符(如「{」)轉換爲它們的百分比編碼的等價物(例如%7B),這不適用於HTTP請求的主體。

需要考慮的另一件事是,你並不需要DataOutputStream這種東西 - 輸出應該是代表一個UTF-8編碼的json文檔的字節流,而DataOuputStream是用於轉換Java原始對象到字節流。你已經有了一個字節流,所以你只需要把它送入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

不解決我的問題。 –