5

Twitter 1.1 API を使用した単純な Java の例を探していましたが、見つかりませんでした。ここに投稿された PHP サンプル: Twitter API バージョン 1.1 で user_timeline を取得するための最も単純な PHP の例およびその他のいくつかの Stackoverflow の投稿を使用して、次の実際の例を思いつくことができました。

public void testUserTimelineWithAuthSample() throws Exception {
    //This will read the timeline of your account.
    String method = "GET";
    String url = "https://api.twitter.com/1.1/statuses/user_timeline.json";

    String oAuthConsumerKey = "Your value here.";
    String oAuthConsumerSecret = "Your value here."; //<--- DO NOT SHARE THIS VALUE

    String oAuthAccessToken = "Your value here.";
    String oAuthAccessTokenSecret = "Your value here."; //<--- DO NOT SHARE THIS VALUE

    String oAuthNonce = String.valueOf(System.currentTimeMillis());
    String oAuthSignatureMethod = "HMAC-SHA1";
    String oAuthTimestamp = time();
    String oAuthVersion = "1.0";

    String signatureBaseString1 = method;
    String signatureBaseString2 = url;
    String signatureBaseString3Templ = "oauth_consumer_key=%s&oauth_nonce=%s&oauth_signature_method=%s&oauth_timestamp=%s&oauth_token=%s&oauth_version=%s";
    String signatureBaseString3 = String.format(signatureBaseString3Templ,
                                                    oAuthConsumerKey, 
                                                    oAuthNonce,
                                                    oAuthSignatureMethod,
                                                    oAuthTimestamp,
                                                    oAuthAccessToken,
                                                    oAuthVersion);

    String signatureBaseStringTemplate = "%s&%s&%s";
    String signatureBaseString =  String.format(signatureBaseStringTemplate, 
                                                                URLEncoder.encode(signatureBaseString1, "UTF-8"), 
                                                                URLEncoder.encode(signatureBaseString2, "UTF-8"),
                                                                URLEncoder.encode(signatureBaseString3, "UTF-8"));

    System.out.println("signatureBaseString: "+signatureBaseString);

    String compositeKey = URLEncoder.encode(oAuthConsumerSecret, "UTF-8") + "&" + URLEncoder.encode(oAuthAccessTokenSecret, "UTF-8");

    String oAuthSignature =  computeSignature(signatureBaseString, compositeKey);
    System.out.println("oAuthSignature       : "+oAuthSignature);

    String oAuthSignatureEncoded = URLEncoder.encode(oAuthSignature, "UTF-8");
    System.out.println("oAuthSignatureEncoded: "+oAuthSignatureEncoded);

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

    String authorizationHeaderValue = String.format(authorizationHeaderValueTempl,
                                                        oAuthConsumerKey,
                                                        oAuthNonce,
                                                        oAuthSignatureEncoded,
                                                        oAuthSignatureMethod,
                                                        oAuthTimestamp,
                                                        oAuthAccessToken,
                                                        oAuthVersion);
    System.out.println("authorizationHeaderValue: "+authorizationHeaderValue);


    System.out.println("url: "+url);
    System.out.println("authorizationHeaderValue:"+authorizationHeaderValue);

    GetMethod getMethod = new GetMethod(url);
    getMethod.addRequestHeader("Authorization", authorizationHeaderValue);
    HttpClient cli = new HttpClient();
    int status = cli.executeMethod(getMethod);
    System.out.println("Status:"+status);

    long responseContentLength = getMethod.getResponseContentLength();
    System.out.println("responseContentLength:"+responseContentLength);

    String response = getMethod.getResponseBodyAsString();  
    System.out.println("response: "+response);
}


private static String computeSignature(String baseString, String keyString) throws GeneralSecurityException, UnsupportedEncodingException, Exception 
{
    SecretKey secretKey = null;

    byte[] keyBytes = keyString.getBytes();
    secretKey = new SecretKeySpec(keyBytes, "HmacSHA1");

    Mac mac = Mac.getInstance("HmacSHA1");

    mac.init(secretKey);

    byte[] text = baseString.getBytes();

    return new String(Base64.encodeBase64(mac.doFinal(text))).trim();
}

private String time() {
    long millis = System.currentTimeMillis();
    long secs = millis / 1000;
    return String.valueOf( secs );
}

ただし、次のようなパラメーターを URL に追加すると:

String url = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=twitterapi&count=2";

私は得る:

応答: {"エラー":[{"メッセージ":"認証できませんでした","コード":32}]}

これがどこで間違っているのか考えていますか?

4

4 に答える 4

0

あなたは間違っていoauth_nonceます。これは、base64でエンコードされたランダムな32バイトの文字列です。

あなたはこのようにそれらを構築することができます:

public String generateNonce() {
    Random gen = new Random(System.currentTimeMillis());
    StringBuilder nonceBuilder = new StringBuilder("");
    String base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    int baseLength = base.length();

    // Taking random word characters
    for (int i = 0; i < 32; ++i) {
        int position = gen.nextInt(baseLength);
        nonceBuilder.append(base.charAt(position));
    }

    String nonce = toBase64(nonceBuilder.toString());

    return nonce;
}

// In your code :
String oAuthNonce = generateNonce();

これString toBase64(String);は、Base64で文字列をエンコードする方法です。

于 2012-11-21T14:37:15.420 に答える
0

以下は、パラメーターを操作する Twitter 1.1 API の例です。この問題はノンスとは関係ありませんでした。それは signatureBaseString でした。signatureBaseString は、アンパサンド (METHOD&URL&PARAMS) で区切られた 3 つの部分の文字列と考えてください。API パラメータは、signatureBaseString の 2 番目の部分に含めるべきではなく、signatureBaseString の最後の部分に (他の 6 つのセキュリティ パラメータとともに) 含める必要があります (また、これらのパラメータはアルファベット順にする必要があります)。

    public void testUserTimelineWithParams() throws Exception {
    //This will read the timeline of the 'twitterapi' account.

    String method = "GET";
    String url = "https://api.twitter.com/1.1/statuses/user_timeline.json";
    List<NameValuePair> urlParams = new ArrayList<NameValuePair>();
    urlParams.add( new NameValuePair("screen_name","twitterapi") );
    urlParams.add( new NameValuePair("count", "10") );

    String oAuthConsumerKey = "Your value";
    String oAuthConsumerSecret = "Your value"; //<--- DO NOT SHARE THIS VALUE

    String oAuthAccessToken = "Your value";
    String oAuthAccessTokenSecret = "Your value"; //<--DO NOT SHARE THIS VALUE

    String oAuthNonce = String.valueOf(System.currentTimeMillis());
    String oAuthSignatureMethod = "HMAC-SHA1";
    String oAuthTimestamp = time();
    String oAuthVersion = "1.0";

    String signatureBaseString1 = method;
    String signatureBaseString2 = url;

    List<NameValuePair> allParams = new ArrayList<NameValuePair>();
    allParams.add(new NameValuePair("oauth_consumer_key", oAuthConsumerKey));
    allParams.add(new NameValuePair("oauth_nonce", oAuthNonce));
    allParams.add(new NameValuePair("oauth_signature_method", oAuthSignatureMethod));
    allParams.add(new NameValuePair("oauth_timestamp", oAuthTimestamp));
    allParams.add(new NameValuePair("oauth_token", oAuthAccessToken));
    allParams.add(new NameValuePair("oauth_version", oAuthVersion));
    allParams.addAll(urlParams);

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

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

    String signatureBaseStringTemplate = "%s&%s&%s";
    String signatureBaseString =  String.format(signatureBaseStringTemplate, 
                                                                URLEncoder.encode(signatureBaseString1, "UTF-8"), 
                                                                URLEncoder.encode(signatureBaseString2, "UTF-8"),
                                                                URLEncoder.encode(signatureBaseString3.toString(), "UTF-8"));

    System.out.println("signatureBaseString: "+signatureBaseString);

    String compositeKey = URLEncoder.encode(oAuthConsumerSecret, "UTF-8") + "&" + URLEncoder.encode(oAuthAccessTokenSecret, "UTF-8");

    String oAuthSignature =  computeSignature(signatureBaseString, compositeKey);
    System.out.println("oAuthSignature       : "+oAuthSignature);

    String oAuthSignatureEncoded = URLEncoder.encode(oAuthSignature, "UTF-8");
    System.out.println("oAuthSignatureEncoded: "+oAuthSignatureEncoded);

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

    String authorizationHeaderValue = String.format(authorizationHeaderValueTempl,
                                                        oAuthConsumerKey,
                                                        oAuthNonce,
                                                        oAuthSignatureEncoded,
                                                        oAuthSignatureMethod,
                                                        oAuthTimestamp,
                                                        oAuthAccessToken,
                                                        oAuthVersion);
    System.out.println("authorizationHeaderValue: "+authorizationHeaderValue);

    StringBuffer urlWithParams = new StringBuffer(url);
    for(int i=0;i<urlParams.size();i++) {
        if(i==0) 
        {
            urlWithParams.append("?");
        }
        else
        {
            urlWithParams.append("&");
        }
        NameValuePair urlParam = urlParams.get(i);
        urlWithParams.append(urlParam.getName() + "=" + urlParam.getValue());
    }

    System.out.println("urlWithParams: "+urlWithParams.toString());
    System.out.println("authorizationHeaderValue:"+authorizationHeaderValue);

    GetMethod getMethod = new GetMethod(urlWithParams.toString());
    getMethod.addRequestHeader("Authorization", authorizationHeaderValue);

    HttpClient cli = new HttpClient();
    int status = cli.executeMethod(getMethod);
    System.out.println("Status:"+status);

    long responseContentLength = getMethod.getResponseContentLength();
    System.out.println("responseContentLength:"+responseContentLength);

    String response = getMethod.getResponseBodyAsString();  
    System.out.println("response: "+response);
}   

private static String computeSignature(String baseString, String keyString) throws GeneralSecurityException, UnsupportedEncodingException, Exception 
{
    SecretKey secretKey = null;

    byte[] keyBytes = keyString.getBytes();
    secretKey = new SecretKeySpec(keyBytes, "HmacSHA1");

    Mac mac = Mac.getInstance("HmacSHA1");

    mac.init(secretKey);

    byte[] text = baseString.getBytes();

    return new String(Base64.encodeBase64(mac.doFinal(text))).trim();
}

private String time() {
    long millis = System.currentTimeMillis();
    long secs = millis / 1000;
    return String.valueOf( secs );
}

NvpComparator の場所:

public class NvpComparator implements Comparator<NameValuePair> {

public int compare(NameValuePair arg0, NameValuePair arg1) {
    String name0 = arg0.getName();
    String name1 = arg1.getName();
    return name0.compareTo(name1);
}

}

于 2012-11-28T03:13:11.257 に答える