首页 文章

401无法验证oauth签名和令牌(https://api.twitter.com/oauth/request_token)(Java代码)

提问于
浏览
1

我尝试从twitter api获取oauth_token但获得异常:
java.io.IOException: Server returned HTTP response code: 401 for URL: https://api.twitter.com/oauth/request_token

Error stream get:
无法验证oauth签名和令牌

Here is a signatureBaseString, signature and Authorization header example :
signatureBaseString :POST&HTTPS%3A%2F%2Fapi.twitter.com%2Foauth%2Frequest_token&oauth_callback%3Dhttp%253A%252F%252F127.0.0.1%253A8080%252Ftwlogin%26oauth_consumer_key%3D2YhNLyum1VY10UrWBMqBnatiT%26oauth_nonce%3D1413642155863%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp% 3D1413642155%26oauth_version%3D1.0

oAuthSignature: Ov4WEws5XULVIxx9n / Q9ybzlrM =

authorizationHeaderValue: OAuth oauth_callback = "http%3A%2F%2F127.0.0.1%3A8080%2Ftwlogin",oauth_consumer_key = "2YhNLyum1VY10UrWBMqBnatiT",oauth_nonce = "1413642155863",oauth_signature = "%2BOv4WEws5XULVIxx9n%2FQ9ybzlrM%3D",oauth_signature_method = "HMAC-SHA1",oauth_timestamp = "1413642155",oauth_version = "1.0"

Here is a code:
NameValuePair比较器:

class NvpComparator implements Comparator<NameValuePair> {
        @Override
        public int compare(NameValuePair arg0, NameValuePair arg1) {
            String name0 = arg0.getName();
            String name1 = arg1.getName();
            return name0.compareTo(name1);
        }
    }

URL编码

class OAuth{
...
    public static String percentEncode(String s) {
            return URLEncoder.encode(s, "UTF-8")
                    .replace("+", "%20").replace("*", "%2A")
                    .replace("%7E", "~");
    }
...
}

请求方法

public String twAuth() {
            String method = "POST";
            String url = "https://api.twitter.com/oauth/request_token";
            String oAuthConsumerKey = "2YhNLyum1VY10UrWBMqBnatiT";
            String oAuthConsumerSecret = ***CONSUMER_SECRET***;
            String oAuthCallback = "http://127.0.0.1:8080/twlogin";
            String oAuthNonce = String.valueOf(System.currentTimeMillis());
            String oAuthSignatureMethod = "HMAC-SHA1";
            String oAuthTimestamp = String.valueOf(System.currentTimeMillis() / 1000);
            String oAuthVersion = "1.0";

            List<NameValuePair> allParams = new ArrayList<NameValuePair>();
            allParams.add(new BasicNameValuePair("oauth_callback", oAuthCallback));
            allParams.add(new BasicNameValuePair("oauth_consumer_key", oAuthConsumerKey));
            allParams.add(new BasicNameValuePair("oauth_nonce", oAuthNonce));
            allParams.add(new BasicNameValuePair("oauth_signature_method", oAuthSignatureMethod));
            allParams.add(new BasicNameValuePair("oauth_timestamp", oAuthTimestamp));
            allParams.add(new BasicNameValuePair("oauth_version", oAuthVersion));

            Collections.sort(allParams, new NvpComparator());

            StringBuffer params = new StringBuffer();
            for(int i=0;i<allParams.size();i++)
            {
                NameValuePair nvp = allParams.get(i);
                if (i>0) {
                    params.append("&");
                }
                params.append(nvp.getName() + "=" + OAuth.percentEncode(nvp.getValue()));
            }

            String signatureBaseStringTemplate = "%s&%s&%s";
            String signatureBaseString =  String.format(signatureBaseStringTemplate,
                    OAuth.percentEncode(method),
                    OAuth.percentEncode(url),
                    OAuth.percentEncode(params.toString()));

            String signatureKey = OAuth.percentEncode(oAuthConsumerSecret)+"&";

        SecretKeySpec signingKey = new SecretKeySpec(signatureKey.getBytes(), "HmacSHA1");
            Mac mac = Mac.getInstance("HmacSHA1");
            mac.init(signingKey);
            byte[] rawHmac = mac.doFinal(signatureBaseString.getBytes());
            String oAuthSignature = new String(Base64.encodeBase64(rawHmac));

        String authorizationHeaderValueTempl = "OAuth oauth_callback=\"%s\", " +
                    "oauth_consumer_key=\"%s\", " +
                    "oauth_nonce=\"%s\", " +
                    "oauth_signature=\"%s\", " +
                    "oauth_signature_method=\"%s\", " +
                    "oauth_timestamp=\"%s\", " +
                    "oauth_version=\"%s\"";

            String authorizationHeaderValue =String.format(authorizationHeaderValueTempl,
                    OAuth.percentEncode(oAuthCallback),
                    OAuth.percentEncode(oAuthConsumerKey),
                    OAuth.percentEncode(oAuthNonce),
                    OAuth.percentEncode(oAuthSignature),
                    OAuth.percentEncode(oAuthSignatureMethod),
                    OAuth.percentEncode(oAuthTimestamp),
                    OAuth.percentEncode(oAuthVersion));

        URL obj = new URL(url);
        HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

        con.setRequestMethod("POST");
        con.setRequestProperty("Authorization", authorizationHeaderValue);

        con.setDoOutput(true);

        int responseCode = con.getResponseCode();
        BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        System.out.println(response.toString());

        return "aboutas";
    }

Here is a twitter application settings:
Consumer Key (API Key): 2YhNLyum1VY10UrWBMqBnatiT
Callback URL: http://127.0.0.1:8080/twlogin
Sign in with Twitter: 是的
Website: http://127.0.0.1:8080

有谁能够帮我?我不知道该怎么办..

1 回答

  • 1

    我设置了错误的时间戳,因为我与Twitter服务器有不同的时区 .

    This is code to set true oAuthTimestamp:

    HttpsURLConnection con = (HttpsURLConnection)
                        new URL("https://api.twitter.com/oauth/request_token").openConnection();
                con.setRequestMethod("HEAD");
                con.getResponseCode();
                String twitterDate= con.getHeaderField("Date");
                DateFormat formatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.ENGLISH);
                Date date = formatter.parse(twitterDate);
                String oAuthTimestamp = String.valueOf(date.getTime()/1000L);
    

相关问题