401 oauth 서명 및 토큰 (https://api.twitter.com/oauth/request_token)의 유효성을 검사하지 못했습니다 (Java 코드).

올렉산드르

Twitter API에서 oauth_token을 얻으려고하는데 예외가 발생합니다.
java.io.IOException: Server returned HTTP response code: 401 for URL: https://api.twitter.com/oauth/request_token

오류 스트림 get :
oauth 서명 및 토큰의 유효성을 검사하지 못했습니다 .

다음은 signatureBaseString, 서명 및 인증 헤더 예제입니다.
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_sigQod = "% 2HxxMAMsig % 2FQod ="% 2HxxMAv4WEws5XUL ", oauth_timestamp ="1413642155 ", oauth_version ="1.0 "

다음은 코드입니다.
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";
    }


다음은 트위터 애플리케이션 설정입니다.
소비자 키 (API 키) : 2YhNLyum1VY10UrWBMqBnatiT
콜백 URL : http://127.0.0.1:8080/twlogin
Twitter로 로그인 :
웹 사이트 : http://127.0.0.1:8080

아무도 나를 도울 수 있습니까? 어떻게 해야할지 모르겠어요 ..

올렉산드르

트위터 서버와 시간대가 다르기 때문에 잘못된 타임 스탬프를 설정했습니다.

이것은 진정한 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);

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

Related 관련 기사

뜨겁다태그

보관