2017-06-02 38 views
0

我想讀取有效的JSON響應,但得到錯誤字符串不能轉換爲JSONObject唐不知道爲什麼。?org.json.JSONException:值java.lang.String類型的<!DOCTYPE不能轉換爲JSONObject而收到有效的JSON響應

的Android代碼

String sendParam = sendParams[0]; 

byte[] sendParamsByte = sendParam.getBytes("UTF-8"); 

HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
conn.setRequestMethod("POST"); 
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
conn.setRequestProperty("Content-Length", String.valueOf(sendParamsByte.length)); 
conn.setDoOutput(true); 
conn.getOutputStream().write(sendParamsByte); 

InputStream responseInputStream = conn.getInputStream(); 
StringBuffer responseStringBuffer = new StringBuffer(); 
byte[] byteContainer = new byte[1024]; 

for (int i; (i = responseInputStream.read(byteContainer)) != -1;) { 
    responseStringBuffer.append(new String(byteContainer, 0, i)); 
} 

JSONObject response = new JSONObject(responseStringBuffer.toString()); 

我的JSON響應 -

{ 
    "firstOne":"XXXXXXXXXX", 
    "secOne":"XXXXXXXXXXXXXXXXXX", 
    "thrOne":"XXXXXXXXXXXXX", 
    "final":"XXXXXXXXXXXXXXX" 
} 

錯誤日誌 -

org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject 
06-02 12:09:13.975 2310-3800/X.x W/System.err:  at org.json.JSON.typeMismatch(JSON.java:111) 
06-02 12:09:13.975 2310-3800/X.x W/System.err:  at org.json.JSONObject.<init>(JSONObject.java:159) 
06-02 12:09:13.975 2310-3800/X.x W/System.err:  at org.json.JSONObject.<init>(JSONObject.java:172) 

任何理念..?

+0

你可以發佈錯誤日誌嗎?並且將你的代碼發佈到解析json的地方。 –

+0

你從服務器得到錯誤 –

+0

可能是你的服務器沒有從你身邊得到適當的參數或檢查你的服務器端代碼 –

回答

-1
conn.setRequestProperty("Content-Length","application/json;charset=UTF-8"); 

更改爲此。

+0

已經嘗試過 – star

+0

你有沒有打印回覆?非常感謝你的迴應? –

+0

它已經在我的問題中作爲示例 – star

-1

檢查發送給服務器的參數是否爲JSON格式。如果他們在JSON格式然後改變你的 「內容類型」 到 「應用/ JSON

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

試圖以這兩種格式發送 – star

+0

誰給了我負面的標記......你能解釋一下爲什麼嗎? –

0

試試這個

  int responseCode=conn.getResponseCode(); 

      if (responseCode == HttpsURLConnection.HTTP_OK) { 

       BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
       StringBuilder sb = new StringBuilder(); 

       String json; 
       while ((json = bufferedReader.readLine()) != null) { 
        sb.append(json + "\n"); 
       } 
       return sb.toString().trim(); 
      } 

你可以從的JSONObject sb.toString()。修剪()。 祝你好運

相關問題