通過使用這個我得到的響應代碼,並試圖將字符串轉換爲JSONObject但得到異常。爲什麼我得到org.json.JSONException:類型java.lang.String的Value屬性不能轉換爲JSONObject?
public JSONObject getJSONFromUrl(String url,List<NameValuePair> nameValuePairsList) {
// Making HTTP request
try {
HttpParams param = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(param, 20000);
HttpConnectionParams.setSoTimeout(param, 20000);
DefaultHttpClient httpClient = new DefaultHttpClient(param);
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairsList));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
PropertyLogger.debug("URL Request: ", url.toString());
PropertyLogger.debug("Encoded Params: ", nameValuePairsList.toString());
HttpResponse httpResponse = httpClient.execute(httpPost);
int code = httpResponse.getStatusLine().getStatusCode();
if (code != 200) {
PropertyLogger.debug("HTTP response code is:", Integer.toString(code));
return null;
} else {
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (ConnectTimeoutException e) {
// TODO: handle exception
PropertyLogger.error("Timeout Exception", e.toString());
return null;
} catch (SocketTimeoutException e) {
// TODO: handle exception
PropertyLogger.error("Socket Time out", e.toString());
return null;
} catch (UnsupportedEncodingException e) {
PropertyLogger.error("UnSupported Exception", e.toString());
e.printStackTrace();
return null;
} catch (ClientProtocolException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
String TAG = "PropertyJsonParser";
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
jsonResp = sb.toString();
PropertyLogger.debug("Content: ", sb.toString());
} catch (Exception e) {
PropertyLogger.error("Buffer Error", "Error converting Response " + e.toString());
return null;
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(jsonResp);
} catch (JSONException e) {
PropertyLogger.error("JSON Parser", "Error parsing data :" + e.toString());
return null;
}
return jObj;
}
登錄jsonResp並告訴我們它是什麼。 –
你沒有得到有效的JSON –
登錄您的jsonResp之前轉換成JSON對象,並檢查它是JSON格式? – LeoMobDev