从网络读取 JSON 数据 (Twitter)
我发现了这个关于如何使用 JSON 检索 Twitter 更新并将其发布在 TextView 中的精彩教程: http://www.ibm.com/developerworks/xml/library/x- andbene1/
我已经按照本教程一步一步进行操作,所以我的代码是相同的。
在方法 examineJSONFile()
中,我们有这样一行:
InputStream is = this.getResources().openRawResource(R.raw.jsontwitter);
这个文件是直接从下载的Twitter 网站,如 http://www.ibm.com/developerworks/xml/library/x-andbene1/#aotf。
所有这一切都很棒,除了一件事:必须下载 Twitter 更新(推文),然后使用它作为原始文件来构建应用程序,这是绝对没有用的。应该可以在运行时下载此 JSON 文件,然后在 TextView 中显示推文。
我尝试以另一种方式创建 InputStream
,如下所示:
String url = "http://twitter.com/statuses/user_timeline/bbcnews.json";
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(new HttpGet(url));
InputStream is = response.getEntity().getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(is,"UTF-8"));
StringBuffer sb = new StringBuffer();
try
{
String line = null;
while ((line = br.readLine())!=null)
{
sb.append(line);
sb.append('\n');
}
}
catch (IOException e)
{
e.printStackTrace();
}
String jsontext = new String(sb.toString());
但似乎这一行: HttpResponse response = httpclient.execute(new HttpGet(url));
抛出一个例外。
有什么帮助吗?
I found this great tutorial on how to use JSON to retrieve Twitter updates, and post it in a TextView:
http://www.ibm.com/developerworks/xml/library/x-andbene1/
I've followed this tutorial step by step, so my code is the same.
In the method examineJSONFile()
, we have this line:
InputStream is = this.getResources().openRawResource(R.raw.jsontwitter);
This file is downloaded directly from the Twitter website, as mentioned in the second paragraph of http://www.ibm.com/developerworks/xml/library/x-andbene1/#aotf.
All this is great, except for one thing: it's absolutely no use that one has to download the Twitter updates (tweets) and then build the app using this as a raw file. It should be possible to download this JSON file at runtime, and then show the tweets in the TextView afterwards.
I have tried to create the InputStream
in another way, like this:
String url = "http://twitter.com/statuses/user_timeline/bbcnews.json";
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(new HttpGet(url));
InputStream is = response.getEntity().getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(is,"UTF-8"));
StringBuffer sb = new StringBuffer();
try
{
String line = null;
while ((line = br.readLine())!=null)
{
sb.append(line);
sb.append('\n');
}
}
catch (IOException e)
{
e.printStackTrace();
}
String jsontext = new String(sb.toString());
But it seems this line: HttpResponse response = httpclient.execute(new HttpGet(url));
throws an exception.
Any help please?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您似乎缺少 INTERNET 权限。看看日志就清楚到底是什么问题了。
You seem to be missing the INTERNET permission. Look at the logs and it would be clear what exactly is the problem.