我正在使用这段代码从Reddit下载json数据。代码在我创建的测试java项目中工作,但在我的Android设备上使用时却没有。在Android设备上,它只会下载一小部分json数据。我无法弄清楚为什么。谢谢你的帮助。
@Override
protected JSONObject doInBackground(URL... urls) {
String c;
StringBuilder str = new StringBuilder();
try {
BufferedReader in = new BufferedReader(new InputStreamReader((InputStream) urls[0].getContent()));
while((c = in.readLine()) != null) {
str.append(c);
}
in.close();
json = new JSONObject(str.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return json;
}
答案 0 :(得分:0)
尝试这种方法
public resultModel getJSONfromReddit() {
resultModel result = new resultModel();
HttpResponse response;
HttpClient myClient = new DefaultHttpClient();
HttpPost myConnection = new HttpPost("http://www.reddit.com/.json");
try {
response = myClient.execute(myConnection);
String JSONString = EntityUtils.toString(response.getEntity(),
"UTF-8");
JSONObject json = null;
json = new JSONObject(JSONString);
Log.i(TAG, JSONString); //this is the whole response but it'll be cutted if you only print it in the eclipse logcat
//PARSE YOUR JSON HERE
}
catch (Exception e) {
e.printStackTrace();
}
return result;
}
也许你的JSON在eclipse控制台中被切断了你可以尝试解析JSON并打印最后的数据来验证它,我希望我的答案很清楚但是如果你想问一些关于我的答案的问题,比如怎么样解析JSON(我假设你知道怎么做)随意在评论中提问:)