使用Volley POST请求获取Twitter身份验证令牌

时间:2015-12-30 15:55:56

标签: android twitter oauth-2.0 android-volley

我正在尝试使用Volley POST请求为Twitter Application only授权令牌生成正确的请求,但我一直收到Http 400响应(错误请求)。

这就是我的尝试:

网址

private static final String TWITTER_API_AUTH_URL = "https://api.twitter.com/oauth2/token";

对消费者密钥和消费者密钥进行编码

try {
    byte[] data = (URLEncoder.encode(TWITTER_CONSUMER_KEY, "UTF-8") + ":" + URLEncoder.encode(TWITTER_CONSUMER_SECRET, "UTF-8")).getBytes("UTF-8");
    mEncodedKeyAndSecret = Base64.encodeToString(data, Base64.DEFAULT);
} catch (UnsupportedEncodingException e) {
    //handleError
}

自定义Volley StringRequest

private class TokenRequestWithAuthHeader extends StringRequest{

    public TokenRequestWithAuthHeader (int method, String url, Response.Listener listener, Response.ErrorListener errorListener)
    {
        super(method, url, listener, errorListener);
    }

    @Override
    public Map getHeaders() throws AuthFailureError {
        Map headers = new HashMap();
        headers.put("Content-Length", String.valueOf(getBody().length));
        headers.put("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
        headers.put("Authorization", "Basic " + mEncodedKeyAndSecret);
        return headers;
    }

    @Override
    public byte[] getBody() {
        return ("grant_type=client_credentials").getBytes();
    }
}

发送请求

tokenRequest = new TokenRequestWithAuthHeader 
                (Request.Method.POST, TWITTER_API_AUTH_URL,  mCallback.getTokenResponseListener(), mCallback);
requestQueue.add(tokenRequest);

Documentation about Application-Only authentication at dev.twitter.com

我还尝试延长JsonObjectRequestJsonRequest而不是StringRequest,结果相同。

有人可以帮助确定请求的问题是什么吗?

2 个答案:

答案 0 :(得分:2)

我刚刚使用您在评论中提供的凭据进行了测试。它使用以下logcat输出(我截断了真实访问令牌的内容)

I/onResponse: {"access_token":"AAAAAAAAAAAAAAAAAAAAAIwbjgAAAAAAGVMKCDU9taD0ke3sStAyA2WKszs%3DA4nfnpLTF31YuE.............JFtKjrTQC1K","token_type":"bearer"}

我的代码:

            final RequestQueue queue = Volley.newRequestQueue(this);
            final String url = "https://api.twitter.com/oauth2/token";
            final String requestBody = "grant_type=client_credentials";
            JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, requestBody, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    Log.i("onResponse", response.toString());
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.e("onErrorResponse", error.toString());
                }
            }) {
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    Map<String, String> headers = new HashMap<>();
                    // Basic Authentication
                    //String auth = "Basic " + Base64.encodeToString(CONSUMER_KEY_AND_SECRET.getBytes(), Base64.NO_WRAP);
                    String auth = "Basic cjMzZXVWeG5ZSDN3NjJ1RUdhV1NtcDAzYzpDa0h5Q3N1ZXF5ZXVobTExWURnTmpKMUZWRFN6OEk5TDFXWXJVUTFQWTNPZTcxcWlGdQ==";
                    headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
                    headers.put("Authorization", auth);
                    return headers;
                }
            };
            queue.add(jsonObjectRequest);

答案 1 :(得分:-1)

private void fetchAccessTokens() {
        final String requestBody = "grant_type=client_credentials";

        JsonObjectRequest req1 = new JsonObjectRequest(Request.Method.POST,
                TwitterTokenURL,
                null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        Log.i("Response: ", response.toString());

                        fetchTweets(response.toString());

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                }){
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> headers = new HashMap<>();

                // URL encode the consumer key and secret
                String urlApiKey = null;
                String urlApiSecret = null;
                try {
                    urlApiKey = URLEncoder.encode(CONSUMER_KEY, "UTF-8");
                    urlApiSecret = URLEncoder.encode(CONSUMER_SECRET, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }

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

                String auth = "Basic "
                        + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
                headers.put("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
                headers.put("Authorization", auth);
                return headers;
            }

            @Override
            public byte[] getBody() {
                return requestBody.getBytes();
            }
        };
        AppController.getInstance().addToRequestQueue(req1, tag_json_arry);

    }