2009-12-20 24 views
3

我正在嘗試twitter流api。我可以使用curl成功地過濾器鳴叫,如前所述hereTwitter流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!

回答

3

我懷疑你需要發佈數據作爲你的HTTP發佈的內容。爲curl -d手冊頁說:

(HTTP)將指定的數據在 POST請求的HTTP服務器,在 同樣的方式,瀏覽器不會當 用戶已填寫的HTML表單和 按下提交按鈕。這將使 導致curl使用內容類型 application/x-www-form-urlencoded將數據傳遞到 服務器。

所以我相信你必須設置該內容類型並將跟蹤文件的內容放在你的文章的正文中。

+0

謝謝Brian的快速幫助,你說得對。我應該有rtfm ... – rdoubleui 2009-12-20 14:39:52