我正在嘗試twitter流api。我可以使用curl成功地過濾器鳴叫,如前所述here:Twitter流API - 設置過濾器在http post request(apache httpcomponents)
curl -d @tracking http://stream.twitter.com/1/statuses/filter.json -u <user>:<pass>
其中tracking
是內容的純文本文件:
track=Berlin
現在我試着做在JavaSE中同樣的事情,使用Apache的HTTPComponents:
UsernamePasswordCredentials creds = new UsernamePasswordCredentials(<user>, <pass>);
DefaultHttpClient httpClient = new DefaultHttpClient();
httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, creds);
HttpPost httpPost = new HttpPost("http://stream.twitter.com/1/statuses/filter.json");
HttpParams params = new BasicHttpParams();
params = params.setParameter("track", "Berlin");
httpPost.setParams(params);
try {
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
String t;
BufferedReader br = new BufferedReader(new InputStreamReader(instream));
while(true) {
t = br.readLine();
if(t != null) {
linkedQueue.offer(t);
}
}
}
} catch (IOException ioe) {
System.out.println(ioe.getMessage());
}
finally{
httpClient.getConnectionManager().shutdown();
}
當我運行的是,我得到:
No filter parameters found. Expect at least one parameter: follow track
作爲我的linkedQueue
中的單個條目。似乎api希望以不同形式顯示參數,但在文檔中找不到任何提示。有人可以與api分享一些經驗,或者看看代碼中的其他問題嗎?謝謝!
編輯 將過濾參數放入參數是一個壞主意。由於它的數據後,需要將其定義爲Entity
正在取得請求之前:
StringEntity postEntity = new StringEntity("track=Berlin", "UTF-8");
postEntity.setContentType("application/x-www-form-urlencoded");
httpPost.setEntity(postEntity);
這是我在做什麼錯。感謝Brian!
謝謝Brian的快速幫助,你說得對。我應該有rtfm ... – rdoubleui 2009-12-20 14:39:52