【发布时间】:2015-09-11 01:24:11
【问题描述】:
我正在尝试使用特殊的#hashtag 抓取推特的推文,并且从返回的 json 中我只需要在 cvs 中导出的推文的 ID、日期、用户 ID、文本。
我的代码如下所示。
import oauth.signpost.OAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.*;
public class CrawlTweets {
static String AccessToken = "xxx";
static String AccessSecret = "xxx";
static String ConsumerKey = "xxx";
static String ConsumerSecret = "xxx";
/**
* @param args
*/
public static void main(String[] args) throws Exception {
OAuthConsumer consumer = new CommonsHttpOAuthConsumer(
ConsumerKey,
ConsumerSecret);
consumer.setTokenWithSecret(AccessToken, AccessSecret);
HttpGet request = new HttpGet("https://api.twitter.com/1.1/search/tweets.json?q=%23Nutella&lang=en");
consumer.sign(request);
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(request);
JSONObject obj = new JSONObject(response);
String id = obj.get("id").toString();
System.out.println(id);
}
}
我得到以下异常:
Exception in thread "main" org.json.JSONException: JSONObject["id"] not found.
at org.json.JSONObject.get(JSONObject.java:459)
at CrawlTweets.main(CrawlTweets.java:41)
代码有什么问题?如何提取上述信息并放入 cvs?谢谢。
【问题讨论】: