gpt4 book ai didi

java - twitter streaming api - 在 http post 请求中设置过滤器(apache httpcomponents)

转载 作者:可可西里 更新时间:2023-11-01 16:12:19 24 4
gpt4 key购买 nike

我正在试用 Twitter 流媒体 API。如 here 所述,我可以使用 curl 成功过滤推文:

curl -d @tracking http://stream.twitter.com/1/statuses/filter.json -u <user>:<pass>

其中 tracking 是一个包含以下内容的普通文件:

track=Berlin

现在我尝试使用 Apache 的 HTTPComponents 在 JavaSE 中做同样的事情:

    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();
}

当我运行它时,我得到:

未找到过滤器参数。至少需要一个参数:follow track

作为我的 linkedQueue 中的单个条目。似乎 api 需要不同形式的参数,但在文档中找不到任何提示。有人可以分享一些使用 api 的经验或看到代码的任何其他问题吗?谢谢!

编辑将过滤器参数放入参数中是个坏主意。由于它是发布数据,因此需要在发出请求之前将其定义为 Entity:

        StringEntity postEntity = new StringEntity("track=Berlin", "UTF-8");
postEntity.setContentType("application/x-www-form-urlencoded");
httpPost.setEntity(postEntity);

这就是我做错的地方。谢谢布莱恩!

最佳答案

我怀疑您需要将数据发布为您的 HTTP 发布的内容curl -d 的手册页说:

(HTTP) Sends the specified data in a POST request to the HTTP server, in the same way that a browser does when a user has filled in an HTML form and presses the submit button. This will cause curl to pass the data to the server using the content-type application/x-www-form-urlencoded.

所以我相信您必须设置该内容类型并将跟踪文件的内容放在您的帖子正文中。

关于java - twitter streaming api - 在 http post 请求中设置过滤器(apache httpcomponents),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1935908/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com