Java twitter流式api-在http post请求中设置过滤器(apache httpcomponents)
我正在试用twitter流媒体api。我可以使用curl成功过滤推文,如下所述: 现在我尝试在JavaSE中使用Apache的HTTPComponents做同样的事情:Java twitter流式api-在http post请求中设置过滤器(apache httpcomponents),java,http,httpwebrequest,twitter,Java,Http,Httpwebrequest,Twitter,我正在试用twitter流媒体api。我可以使用curl成功过滤推文,如下所述: 现在我尝试在JavaSE中使用Apache的HTTPComponents做同样的事情: UsernamePasswordCredentials creds = new UsernamePasswordCredentials(<user>, <pass>); DefaultHttpClient httpClient = new DefaultHttpClient();
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();
}
这就是我做错的。谢谢你,布莱恩 我怀疑您需要将数据作为HTTP post的内容发布。
curl-d
的手册页显示:
(HTTP)以指定的格式发送指定的数据
在中向HTTP服务器发送请求
与浏览器在
用户已填写HTML表单,并且
按下提交按钮。这将
使curl将数据传递给
使用内容类型的服务器
application/x-www-form-urlencoded
因此,我认为您必须设置该内容类型,并将跟踪文件的内容放在帖子的正文中
track=Berlin
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();
}
StringEntity postEntity = new StringEntity("track=Berlin", "UTF-8");
postEntity.setContentType("application/x-www-form-urlencoded");
httpPost.setEntity(postEntity);