首页 > 解决方案 > 使用 OAuth 1.0 请求 Twitter api

问题描述

我正在尝试使用 Twitter 的朋友列表 api,并且在没有任何参数的情况下成功地这样做了。

但是,每当我添加参数时,我都会收到错误“无法验证您”。cursor而好友列表太长的时候,我只好加个参数。

当我在没有任何参数的情况下调用 api 时,我得到了朋友的用户列表,这一事实让我认为验证请求可以正常工作。

我试图将请求 url 更改为https://api.twitter.com/1.1/friends/list.json?cursor=-1这给了我身份验证错误。

我尝试同时使用https://api.twitter.com/1.1/friends/list.jsonhttps://api.twitter.com/1.1/friends/list.json?cursor=-1来制作 oauth_signature 和它们让我失望了。

我尝试使用不同的参数,例如 screen_name 或 user_id,它们都会给我同样的错误。

我什至尝试cursor: -1像 POST 请求一样添加标头,但这也不起作用。

现在我的代码看起来像这样

public String getFriendList() {
    String baseUrl = "https://api.twitter.com/1.1/friends/list.json";

    // Creates a map with all necessary headers
    Map<String, String> headers = createMap(); 
    headers.put("oauth_token", <OAuth token of user>);
    String signature = createSignature("GET", baseUrl, headers, <OAuth secret of user>);

    // Add oauth_signature to header
    headers.put("oauth_signature", signature);

    String body = sendGetRequest(baseUrl, headers);
    return body;
}

public String sendGetRequest(String baseUrl, Map<String, String> parameters) throws AuthException, IOException {
    try (CloseableHttpClient client = CloseableHttpClientFactory.getHttpClient()) {
        HttpGet httpGet = new HttpGet(baseUrl);

        if (parameters != null) {
            httpGet.setHeader("Authorization", createHeader(parameters));
        }

        CloseableHttpResponse response = client.execute(httpGet);

        if (response.getStatusLine().getStatusCode() != 200) {
            LOGGER.info("GET Request Failed : " + EntityUtils.toString(response.getEntity()));
            throw new Exception();
        }

        String responseBody = EntityUtils.toString(response.getEntity());
        return responseBody;
    }
}

这是工作代码。

谁能告诉我在哪里添加参数以及我在验证请求时遗漏了什么?

编辑:添加了 sendGetRequest 的代码。按照 twitter 的文档进行签名和添加标题

标签: javaspring-boottwittertwitter-oauth

解决方案


推荐阅读