Created
August 30, 2010 11:02
-
-
Save vvakame/557292 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package oauth; | |
import java.io.IOException; | |
import java.io.OutputStream; | |
import java.security.InvalidKeyException; | |
import java.security.NoSuchAlgorithmException; | |
import java.util.ArrayList; | |
import java.util.LinkedHashMap; | |
import java.util.List; | |
import java.util.Set; | |
import com.shin1ogawa.oauth.OAuthUtil; | |
public class OAuth { | |
final static String URL = "http://gdd-2010-quiz-japan.appspot.com/oauth/5ea045ed0d74797db5b1659a"; | |
final static String CONSUMER_KEY = "5ea045ed0d74797db5b1659a"; | |
final static String CONSUMER_SECRET = "db75fc64691b6bf2dd0415a1"; | |
final static String BODY = "hello=world"; | |
// final static String BODY = ""; | |
public static void main(String[] args) throws InvalidKeyException, | |
NoSuchAlgorithmException, IOException { | |
java.util.Map<String, String> params = new LinkedHashMap<String, String>(); | |
params.put("hello", "world"); | |
params.put("oauth_consumer_key", CONSUMER_KEY); | |
params.put("oauth_nonce", String.valueOf((long) (Math.random() * Math | |
.pow(2.0, 64.0)))); | |
params.put("oauth_signature_method", "HMAC-SHA1"); | |
params.put("oauth_timestamp", String | |
.valueOf(System.currentTimeMillis() / 1000)); | |
String signature = OAuthUtil.generateOauthSignature(OAuthUtil | |
.generateSignatureBaseString("POST", URL, params), | |
CONSUMER_SECRET, ""); // empty tokenSecret | |
params.put("realm", "devquiz"); | |
params.put("oauth_signature", signature); | |
StringBuilder stb = new StringBuilder(); | |
Set<String> set = params.keySet(); | |
stb.append("OAuth "); | |
List<String> list = new ArrayList<String>(); | |
for (String key : set) { | |
list.add(key + "=\"" + params.get(key) + "\""); | |
} | |
for (int i = 0; i < list.size(); i++) { | |
stb.append(list.get(i)); | |
if (list.size() - 1 != i) { | |
stb.append(","); | |
} | |
} | |
java.net.URL url = new java.net.URL(URL); | |
java.net.HttpURLConnection connection = (java.net.HttpURLConnection) url | |
.openConnection(); | |
connection.setDoInput(true); | |
connection.setDoOutput(true); | |
connection.setRequestMethod("POST"); | |
connection.setRequestProperty("Content-Length", String.valueOf(BODY | |
.getBytes().length)); | |
connection.setRequestProperty("Authorization", stb.toString()); | |
OutputStream os = connection.getOutputStream(); | |
os.write(BODY.getBytes()); | |
os.flush(); | |
os.close(); | |
connection.connect(); | |
String response = getResponseAsString(connection); | |
response.toString(); | |
} | |
static final String getResponseAsString( | |
java.net.HttpURLConnection connection) throws java.io.IOException { | |
java.io.BufferedReader in = null; | |
try { | |
in = new java.io.BufferedReader(new java.io.InputStreamReader( | |
connection.getInputStream())); | |
} catch (java.io.IOException ex) { | |
throw new RuntimeException(String.format("IOException: [%d]%s", | |
connection.getResponseCode(), connection | |
.getResponseMessage())); | |
} | |
StringBuilder b = new StringBuilder(); | |
String line; | |
while ((line = in.readLine()) != null) { | |
b.append(line); | |
} | |
in.close(); | |
return b.toString(); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.shin1ogawa.oauth; | |
public class OAuthUtil { | |
static final String ENC = "utf-8"; | |
static final String HMAC_SHA1_ALGORITHM = "HmacSHA1"; | |
public static String generateSignatureBaseString(String method, | |
String requestUrlBase, java.util.Map<String, String> params) | |
throws java.io.UnsupportedEncodingException { | |
return escapeAndJoin(java.util.Arrays.asList(method, requestUrlBase, | |
formatUrlParams(params))); | |
} | |
public static String generateOauthSignature(String baseString, | |
String consumerSecret, String tokenSecret) | |
throws java.security.InvalidKeyException, | |
java.security.NoSuchAlgorithmException, | |
java.io.UnsupportedEncodingException { | |
return java.net.URLEncoder.encode(generateHmacSha1Signature(baseString, | |
escapeAndJoin(java.util.Arrays.asList(consumerSecret, | |
tokenSecret))), ENC); | |
} | |
public static String formatUrlParams(java.util.Map<String, String> params) | |
throws java.io.UnsupportedEncodingException { | |
StringBuilder b = new StringBuilder(); | |
boolean first = true; | |
for (String key : sorted(params)) { | |
if (first == false) { | |
b.append('&'); | |
} else { | |
first = false; | |
} | |
b.append(key).append('=').append( | |
java.net.URLEncoder.encode(params.get(key), ENC).replace( | |
"+", "%20")); | |
} | |
return b.toString(); | |
} | |
private static String escapeAndJoin(Iterable<String> params) | |
throws java.io.UnsupportedEncodingException { | |
StringBuilder b = new StringBuilder(); | |
boolean first = true; | |
for (String s : params) { | |
if (first == false) { | |
b.append('&'); | |
} else { | |
first = false; | |
} | |
b.append(java.net.URLEncoder.encode(s, ENC)); | |
} | |
return b.toString(); | |
} | |
private static java.util.List<String> sorted( | |
java.util.Map<String, String> map) { | |
java.util.List<String> list = new java.util.ArrayList<String>(map | |
.keySet()); | |
java.util.Collections.sort(list); | |
return list; | |
} | |
private static String generateHmacSha1Signature(String data, String key) | |
throws java.security.NoSuchAlgorithmException, | |
java.security.InvalidKeyException { | |
javax.crypto.spec.SecretKeySpec signingKey = new javax.crypto.spec.SecretKeySpec( | |
key.getBytes(), HMAC_SHA1_ALGORITHM); | |
javax.crypto.Mac mac = javax.crypto.Mac | |
.getInstance(HMAC_SHA1_ALGORITHM); | |
mac.init(signingKey); | |
return byteArrayToBase64(mac.doFinal(data.getBytes())); | |
} | |
private static String byteArrayToBase64(byte[] bytes) { | |
int aLen = bytes.length; | |
int numFullGroups = aLen / 3; | |
int numBytesInPartialGroup = aLen - 3 * numFullGroups; | |
int resultLen = 4 * ((aLen + 2) / 3); | |
StringBuilder b = new StringBuilder(resultLen); | |
int inCursor = 0; | |
for (int i = 0; i < numFullGroups; i++) { | |
int byte0 = bytes[inCursor++] & 0xff; | |
int byte1 = bytes[inCursor++] & 0xff; | |
int byte2 = bytes[inCursor++] & 0xff; | |
b.append(intToBase64[byte0 >> 2]); | |
b.append(intToBase64[(byte0 << 4) & 0x3f | (byte1 >> 4)]); | |
b.append(intToBase64[(byte1 << 2) & 0x3f | (byte2 >> 6)]); | |
b.append(intToBase64[byte2 & 0x3f]); | |
} | |
if (numBytesInPartialGroup != 0) { | |
int byte0 = bytes[inCursor++] & 0xff; | |
b.append(intToBase64[byte0 >> 2]); | |
if (numBytesInPartialGroup == 1) { | |
b.append(intToBase64[(byte0 << 4) & 0x3f]); | |
b.append("=="); | |
} else { | |
int byte1 = bytes[inCursor++] & 0xff; | |
b.append(intToBase64[(byte0 << 4) & 0x3f | (byte1 >> 4)]); | |
b.append(intToBase64[(byte1 << 2) & 0x3f]); | |
b.append('='); | |
} | |
} | |
return b.toString(); | |
} | |
private static final char intToBase64[] = { 'A', 'B', 'C', 'D', 'E', 'F', | |
'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', | |
'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', | |
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', | |
't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', | |
'6', '7', '8', '9', '+', '/' }; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment