public JSONObject getJSONFromUrl(String url) {
InputStream is = null;
JSONObject jObj = null;
String json = "";
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
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();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
我GOOGLE了很多從url獲取json字符串,但我認爲是時候問我這個問題了。幾乎所有這個問題的算法都不適合我。它確實需要與AsyncTask一起使用嗎?我在Android的初學者,所以我不知道很多。請幫幫我。或者,如果您可以提供更好的算法,請這樣做。總是意外停止
你可以發佈堆棧跟蹤嗎? – Raghunandan
你面臨什麼錯誤?沒有錯誤=沒有幫助。 – GrIsHu
你是否以json的形式從服務器獲得任何響應? –