使用 Apache HttpClient 和 Oauth 路标连接到 Twitter 流媒体 API 并使用带有空格的轨道?

发布于 2024-09-30 21:43:39 字数 3813 浏览 1 评论 0原文

下面是一些尝试使用带有空格(“you will”)的曲目连接到 Twitter 的代码。它使用 Apache HttpClientsignpost oauth 或多或少类似于 tweetstream4j 确实如此。我使用

  • signpost-core-1.2.1.1.jar
  • signpost-commonshttp4-1.2.1.1.jar
  • httpclient-4.0.1.jar
  • httpcore-4.0.1.jar

如果我运行代码,我会从 Twitter 收到“401 未经授权”。如果使用不带空格的轨道(例如,“will”而不是“you will”),它可以正常连接并正常工作(只要我用有效值填写 oauth 消费者密钥和秘密、令牌和令牌秘密)。

有人发现问题所在吗?我认为这与 POST 正文中的 track 参数的 URL 编码有关,但我不确定。我一直在研究路标的工作原理,直到我的眼睛流血。

(这与 Java 中带有轨道的 Twitter 流 API 有关有空格吗?)。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.logging.Logger;

import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.exception.OAuthCommunicationException;
import oauth.signpost.exception.OAuthExpectationFailedException;
import oauth.signpost.exception.OAuthMessageSignerException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;

public class TwitterSpaceTest {
private static Logger logger = Logger.getLogger(
    TwitterSpaceTest.class.getName());

private static final String API_PROTOCOL = "http";
private static final String API_DOMAIN = "stream.twitter.com";
private static final String API_URL = "1/";
private static final String FILTER_URL = API_URL + "statuses/filter.json";

public static void readFrom(HttpRequestBase requestMethod) throws IOException {
    DefaultHttpClient client = new DefaultHttpClient();
    HttpResponse response = client.execute(requestMethod);
    HttpEntity entity = response.getEntity();
    if (entity == null) throw new IOException("No entity");
    BufferedReader br = new BufferedReader(new InputStreamReader(
        entity.getContent(), "UTF-8"));
    while (true) {
       String line = br.readLine();
       if (line != null && !line.isEmpty()) {
       System.out.println(line);
       }
    }
}

public static HttpRequestBase getConnection()
    throws OAuthMessageSignerException,
    OAuthExpectationFailedException, OAuthCommunicationException,
    IllegalStateException, IOException {
    String base = FILTER_URL;
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    // No spaces
//        params.add(new BasicNameValuePair("track", "will"));
    // Spaces
    params.add(new BasicNameValuePair("track", "you will"));

    HttpPost method = new HttpPost(API_PROTOCOL + "://" + API_DOMAIN + "/"
        + base);
    logger.info("" + method.getURI());

    UrlEncodedFormEntity postEntity = new UrlEncodedFormEntity(params,
        HTTP.UTF_8);
    method.setEntity(postEntity);

    String consumerKey = "...";
    String consumerSecret = "..."
    CommonsHttpOAuthConsumer consumer = new CommonsHttpOAuthConsumer(
        consumerKey, consumerSecret);
    String token = "...";
    String tokenSecret = "...";
    consumer.setTokenWithSecret(token, tokenSecret);
    consumer.sign(method);

    return method;
}

public static void main(String[] args) throws Exception {
    readFrom(getConnection());
}
}

Below is some code that tries to connect to Twitter using tracks with a space ("you will"). It uses Apache HttpClient and signpost oauth in more or less the manner tweetstream4j does. I use

  • signpost-core-1.2.1.1.jar
  • signpost-commonshttp4-1.2.1.1.jar
  • httpclient-4.0.1.jar
  • httpcore-4.0.1.jar

If I run the code, I get "401 unauthorized" from Twitter. If use tracks without spaces (e.g., "will" instead of "you will"), it connects and works fine (as long as I fill in oauth consumer key and secret, token, and token secret with valid values).

Does anyone spot the problem? I think it has to do with the URL encoding of the tracks parameter in the POST body, but I'm not sure. I've been digging into how signpost works until my eyes bleed.

(This is related to Twitter streaming API in Java with tracks that have spaces?).

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.logging.Logger;

import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.exception.OAuthCommunicationException;
import oauth.signpost.exception.OAuthExpectationFailedException;
import oauth.signpost.exception.OAuthMessageSignerException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;

public class TwitterSpaceTest {
private static Logger logger = Logger.getLogger(
    TwitterSpaceTest.class.getName());

private static final String API_PROTOCOL = "http";
private static final String API_DOMAIN = "stream.twitter.com";
private static final String API_URL = "1/";
private static final String FILTER_URL = API_URL + "statuses/filter.json";

public static void readFrom(HttpRequestBase requestMethod) throws IOException {
    DefaultHttpClient client = new DefaultHttpClient();
    HttpResponse response = client.execute(requestMethod);
    HttpEntity entity = response.getEntity();
    if (entity == null) throw new IOException("No entity");
    BufferedReader br = new BufferedReader(new InputStreamReader(
        entity.getContent(), "UTF-8"));
    while (true) {
       String line = br.readLine();
       if (line != null && !line.isEmpty()) {
       System.out.println(line);
       }
    }
}

public static HttpRequestBase getConnection()
    throws OAuthMessageSignerException,
    OAuthExpectationFailedException, OAuthCommunicationException,
    IllegalStateException, IOException {
    String base = FILTER_URL;
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    // No spaces
//        params.add(new BasicNameValuePair("track", "will"));
    // Spaces
    params.add(new BasicNameValuePair("track", "you will"));

    HttpPost method = new HttpPost(API_PROTOCOL + "://" + API_DOMAIN + "/"
        + base);
    logger.info("" + method.getURI());

    UrlEncodedFormEntity postEntity = new UrlEncodedFormEntity(params,
        HTTP.UTF_8);
    method.setEntity(postEntity);

    String consumerKey = "...";
    String consumerSecret = "..."
    CommonsHttpOAuthConsumer consumer = new CommonsHttpOAuthConsumer(
        consumerKey, consumerSecret);
    String token = "...";
    String tokenSecret = "...";
    consumer.setTokenWithSecret(token, tokenSecret);
    consumer.sign(method);

    return method;
}

public static void main(String[] args) throws Exception {
    readFrom(getConnection());
}
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

记忆之渊 2024-10-07 21:43:39

您应该将 api 链接中的 http 更改为 https

you should change the http to https in api link

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文