gpt4 book ai didi

java - 使用 Twitter API 1.1 和 Retrofit 检索给定用户的推文列表

转载 作者:太空宇宙 更新时间:2023-11-04 13:53:44 24 4
gpt4 key购买 nike

我正在尝试获取用户的推文列表,但在尝试验证对 API 的调用时遇到了一些麻烦。目前,我在执行以下代码时收到 401 错误:

    public interface TwitterApi {

String API_URL = "https://api.twitter.com/1.1";

String CONSUMER_KEY = "<CONSUMER KEY GOES HERE>";
String CONSUMER_SECRET = "<CONSUMER SECRET GOES HERE>";
String ACCESS_TOKEN = "<ACCESS TOKEN GOES HERE>";
String ACCESS_TOKEN_SECRET = "<ACCESS TOKEN SECRET GOES HERE>";

@GET("/statuses/user_timeline.json")
List<Tweet> fetchUserTimeline(
@Query("count") final int count,
@Query("screen_name") final String screenName);
}

调用 fetchUserTimeline() 时,以下内容会引发 401 授权错误

RetrofitHttpOAuthConsumer consumer = new RetrofitHttpOAuthConsumer(TwitterApi.CONSUMER_KEY, TwitterApi.CONSUMER_SECRET);
consumer.setTokenWithSecret(TwitterApi.ACCESS_TOKEN, TwitterApi.ACCESS_TOKEN_SECRET);
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(TwitterApi.API_URL)
.setClient(new SigningOkClient(consumer))
.build();


TwitterApi twitterApi = restAdapter.create(TwitterApi.class)

tweets = twitterApi.fetchUserTimeline(2, screenName);

我还包含了路标改造插件中的相关代码:

public class SigningOkClient extends OkClient {

private final RetrofitHttpOAuthConsumer mOAuthConsumer;

public SigningOkClient(RetrofitHttpOAuthConsumer consumer) {
mOAuthConsumer = consumer;
}

public SigningOkClient(OkHttpClient client, RetrofitHttpOAuthConsumer consumer) {
super(client);
mOAuthConsumer = consumer;
}

@Override
public Response execute(Request request) throws IOException {
Request requestToSend = request;
try {
HttpRequestAdapter signedAdapter = (HttpRequestAdapter) mOAuthConsumer.sign(request);
requestToSend = (Request) signedAdapter.unwrap();
} catch (OAuthMessageSignerException | OAuthExpectationFailedException | OAuthCommunicationException e) {
// Fail to sign, ignore
e.printStackTrace();
}
return super.execute(requestToSend);
}

}

路标改造插件可以在这里找到:https://github.com/pakerfeldt/signpost-retrofit

public class RetrofitHttpOAuthConsumer extends AbstractOAuthConsumer {

private static final long serialVersionUID = 1L;

public RetrofitHttpOAuthConsumer(String consumerKey, String consumerSecret) {
super(consumerKey, consumerSecret);
}

@Override
protected HttpRequest wrap(Object request) {
if (!(request instanceof retrofit.client.Request)) {
throw new IllegalArgumentException("This consumer expects requests of type " + retrofit.client.Request.class.getCanonicalName());
}
return new HttpRequestAdapter((Request) request);
}
}

这里的任何帮助都会很棒。该解决方案不必包含路标的使用,但我确实想使用 Retrofit。我也不想希望在 WebView 中向用户显示“使用 Twitter 进行身份验证”屏幕 - 我只想显示一些相关推文作为详细信息 View 的一部分。

最佳答案

您确定路标改造项目适用于 twitter oauth 吗?我过去曾成功使用过 twitter4j - 如果您不需要完整的库,您可以使用他们的代码作为引用。 twitter4j

关于java - 使用 Twitter API 1.1 和 Retrofit 检索给定用户的推文列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30041460/

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