简体   繁体   中英

org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject while receiving valid JSON response

I am trying to read the valid JSON response but getting the error String cannot be converted to JSONObject don't know why.?

android code

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());

My JSON Response -

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

error log -

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)

Any idea..?

Try this

            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();
            }

you can get JSONObject from sb.toString().trim(). good luck

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

改成这个。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM