Newer
Older
RestfulChecker / src / testcase / twitter / OAuthHeader.java
y-ota on 7 Jan 2019 3 KB サーバー復旧
package testcase.twitter;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map.Entry;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import sun.misc.BASE64Encoder;

public class OAuthHeader {
	private String consumer_key = "";
	private String consumer_secret = "";
	private String oauth_token = "";
	private String oauth_secret = "";
	private String method = "POST";
	private String url = "https://api.twitter.com/oauth/request_token";
	private SortedMap<String, String> params = new TreeMap<String, String>();

	public static void main(String[] args) throws Exception {
		// OAuthにおいて利用する変数宣言
		String consumerkey = "xPk6o11catewYwxGcXvvvqo2I";
		String consumerSecret = "P9oXQstrFURXcbV8qT4OJzLjNfgYkpo1AvJzUnbywsEiDpuytb";
		String oauthToken = "E7D28QAAAAAA9Im2AAABaCZ6YNc";
		String oauthTokenSecret = "zdhnHCamrW3jLSb3GbwhVlnmJZsOqX1V";
		String method = "POST";
		String urlStr = "https://api.twitter.com/oauth/access_token";

		// 共通パラメーター
		SortedMap<String, String> params = new TreeMap<String, String>();
		params.put("oauth_consumer_key", consumerkey);
		params.put("oauth_signature_method", "HMAC-SHA1");
		params.put("oauth_timestamp", String.valueOf(getUnixTime()));
		params.put("oauth_nonce", String.valueOf(Math.random()));
		params.put("oauth_version", "1.0");
		params.put("oauth_token", oauthToken);

		// アクセストークン取得時にのみ利用するパラメーター
		// アプリケーションの許可をした場合に表示される暗証番号を設定する
		params.put("oauth_verifier", "暗証番号");

		{
			/*
			 * 署名(oauth_signature)の生成
			 * リクエストトークン取得時と全く同じ処理
			 */
			String paramStr = "";
			for (Entry<String, String> param : params.entrySet()) {
				paramStr += "&" + param.getKey() + "=" + param.getValue();
			}
			paramStr = paramStr.substring(1);

			String text = method + "&" + urlEncode(urlStr) + "&"
					+ urlEncode(paramStr);

			String key = urlEncode(consumerSecret) + "&"
					+ urlEncode(oauthTokenSecret);

			SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(),
					"HmacSHA1");
			Mac mac = Mac.getInstance(signingKey.getAlgorithm());
			mac.init(signingKey);
			byte[] rawHmac = mac.doFinal(text.getBytes());
			String signature = new BASE64Encoder().encode(rawHmac);

			params.put("oauth_signature", signature);
		}

		/*
		 * Authorizationヘッダの作成とAPIの呼び出し
		 * リクエストトークン取得時と全く同じ処理
		 */
		// Authorizationヘッダの作成
		String paramStr = "";
		for (Entry<String, String> param : params.entrySet()) {
			paramStr += ", " + param.getKey() + "=\""
					+ urlEncode(param.getValue()) + "\"";
		}
		paramStr = paramStr.substring(2);
		String authorizationHeader = "OAuth " + paramStr;

		// APIにアクセス
		URL url = new URL(urlStr);
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.setRequestMethod(method);
		connection.setRequestProperty("Authorization", authorizationHeader);
		connection.connect();
		BufferedReader reader = new BufferedReader(new InputStreamReader(
				connection.getInputStream()));
		String response;
		while ((response = reader.readLine()) != null) {
			System.out.println(response);
		}
	}

	private static int getUnixTime() {
		return (int) (System.currentTimeMillis() / 1000L);
	}

	private static String urlEncode(String string) {
		try {
			return URLEncoder.encode(string, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}
	}
}