2

我正在使用 twitter 的文档来关注用户,使用下面的 url https://dev.twitter.com/rest/reference/post/friendships/create

在使用 api https://api.twitter.com/1.1/friendships/create.json?user_id=1401881&follow=true时,我收到 403 错误,

调用api的代码如下。

public String getTwitterFollow(String url) {

        //?screen_name=MDforLives&follow=true

        String results = null;
        // Step 1: Encode consumer key and secret
        try {
            // URL encode the consumer key and secret
            String urlApiKey = URLEncoder.encode(CONSUMER_KEY, "UTF-8");
            String urlApiSecret = URLEncoder.encode(CONSUMER_SECRET, "UTF-8");

            // Concatenate the encoded consumer key, a colon character, and the
            // encoded consumer secret
            String combined = urlApiKey + ":" + urlApiSecret;

            // Base64 encode the string
            String base64Encoded = Base64.encodeToString(combined.getBytes(), Base64.NO_WRAP);

            // Step 2: Obtain a bearer token
            HttpPost httpPost = new HttpPost(TwitterTokenURL);
            httpPost.setHeader("Authorization", "Basic " + base64Encoded);
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
            httpPost.setEntity(new StringEntity("grant_type=client_credentials"));
            String rawAuthorization = getResponseBody(httpPost);
            Authenticated auth = jsonToAuthenticated(rawAuthorization);

            // Applications should verify that the value associated with the
            // token_type key of the returned object is bearer
            if (auth != null && auth.token_type.equals("bearer")) {

                url = url.replaceAll(" ", "%20");

                // Step 3: Authenticate API requests with bearer token
                HttpPost httpGet = new HttpPost(url);

                // construct a normal HTTPS request and include an Authorization
                // header with the value of Bearer <>
                httpGet.setHeader("Authorization", "Bearer " + auth.access_token);
               // httpGet.setHeader("Content-Type", "application/json");

                StringEntity stringEntity;

                JSONObject obj=new JSONObject();

                obj.put("screen_name","MDforLives");
                obj.put("follow","true");

                stringEntity = new StringEntity(obj.toString());
                stringEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
               // httpGet.setEntity(stringEntity);

                // update the results with the body of the response
                results = getResponseBody(httpGet);

                System.out.println("results returns" + results);

            }
        } catch (Exception ex) {
        }
        return results;
    }

因此,请建议 url 有什么问题,或者 android 端是否有任何代码问题。

4

1 回答 1

3

来自官方文档

如果您已经是用户的朋友,则可能会返回 HTTP 403,但出于性能原因,即使友谊已经存在,您也可能会收到 200 OK 消息。

这种行为可能是正常的;)

于 2016-11-08T21:26:45.850 回答