【发布时间】:2014-11-01 14:45:05
【问题描述】:
我正在使用 Twitter 搜索 API 来获取给定搜索字符串上的推文计数。由于 API 仅返回 URL 中“count”参数指定的推文数量,因此我必须多次向 URL 发送 REST 调用。
我解析第一次调用后返回的 JSON 响应并获取最后一条推文的 ID,并在下次将其作为“max_id”发送到 URL 中以获取更多推文。
代码如下:
private static void sendSearchRequest(String token, String maxId) throws Exception {
System.out.println("Entering sendSearchRequest");
byte[] temp = Base64.encodeBase64(token.getBytes());
String url = "https://api.twitter.com/1.1/search/tweets.json?q=%23SearchString&count=100&include_entities=false";
//Will be null in first invocation, not null in subsequent calls
if(maxId != null)
url += "&max_id="+maxId;
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
con.setRequestProperty("Authorization", "Bearer " + token);
System.out.println("\nSending 'GET' request to URL : " + url);
// optional default is GET
con.setRequestMethod("GET");
int responseCode = con.getResponseCode();
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
con.disconnect();
//Resend the request till response is not blank.
if(response.toString().length() > 0){
maxId = parseResponse(response.toString());
System.out.println(positiveCount);
sendSearchRequest(token, maxId);
}else{
System.out.println("No more results");
return;
}
System.out.println("Exiting parseResponse");
}
private static String parseResponse(String response) {
System.out.println("Entering parseResponse");
String lastId = "";
JSONParser parser=new JSONParser();
try{
Object object = parser.parse(response);
JSONObject array = (JSONObject)object;
JSONArray jsonArray = (JSONArray)array.get("statuses");
int size = jsonArray.size();
positiveCount += size;
System.out.println(size);
//Find the index of last object in the array returned by API
JSONObject lastObject = (JSONObject)jsonArray.get(size-1);
//Get Tweet ID to be set as Max_id in next call to Twitter.
Long id = (Long)lastObject.get("id");
System.out.println(id);
lastId = id+"";
}catch(Exception e){
e.printStackTrace();
}
System.out.println("Exiting parseResponse");
return lastId;
}
我面临的问题是这段代码只调用了几次。之后,不会发送呼叫,程序只是挂起。我怀疑这可能是由于过时的打开连接,所以我手动关闭了它,但即使这样也不起作用。
谁能告诉我这里出了什么问题?
谢谢 阿布舍克
【问题讨论】:
-
也许是 api 限制了你。 dev.twitter.com/docs/rate-limiting/1.1
-
我什至没有提出这么多要求:(
-
得到了问题。这是 Twitter API 中的某种错误/限制。 dev.twitter.com/discussions/34598 我对上面的代码做了一些改动,并在发送调用 Twitter API 之前放入了 Thread.sleep(20000) 并且它工作正常。虽然非常慢:(
-
我猜是没办法了。很高兴您找到了解决方案。将其发布为答案并标记它,因此可以认为该主题已解决。