Created
February 22, 2011 02:07
-
-
Save takeshy/838095 to your computer and use it in GitHub Desktop.
OAuth Consumer Request(2-legged OAuth)
This file contains 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
import java.net.URI | |
import org.apache.http._ | |
import org.apache.http.client._ | |
import org.apache.http.impl.client._ | |
import org.apache.http.entity.InputStreamEntity | |
import org.apache.http.client.methods._ | |
import scala.util.parsing.json.JSON._ | |
import java.io.StringBufferInputStream | |
import org.apache.commons.codec.binary.Base64.encodeBase64 | |
import javax.crypto | |
import scala.collection.immutable.TreeMap | |
import scala.collection.mutable.ListBuffer | |
def sign(method: String, url: String,consumer_key:String,consumer_secret:String,xoauth_requestor_id:String) = { | |
val oauth_params = Map( | |
"oauth_consumer_key" -> consumer_key, | |
"oauth_nonce" -> System.nanoTime.toString, | |
"oauth_signature_method" -> "HMAC-SHA1", | |
"oauth_timestamp" -> (System.currentTimeMillis / 1000).toString, | |
"oauth_version"->"1.0", | |
"xoauth_requestor_id" -> xoauth_requestor_id | |
) | |
val encoded_ordered_params = ( | |
new TreeMap[String, String] ++ oauth_params | |
) map { case (k, v) => k + "=" + v } mkString "&" | |
val message = (method :: java.net.URLEncoder.encode(url,"UTF-8") :: java.net.URLEncoder.encode(encoded_ordered_params,"UTF-8") :: Nil).mkString("&") | |
val SHA1 = "HmacSHA1"; | |
val key_str = consumer_secret + "&" | |
val key = new crypto.spec.SecretKeySpec(key_str.getBytes("UTF-8"), SHA1) | |
val sig = { | |
val mac = crypto.Mac.getInstance(SHA1) | |
mac.init(key) | |
new String(encodeBase64(mac.doFinal(message.getBytes("UTF-8")))) | |
} | |
oauth_params + ("oauth_signature" -> sig) | |
} | |
val CONSUMER_KEY="????????????????????" | |
val CONSUMER_SECRET="?????????????????" | |
val GAME_ID = "??????????????" | |
val url = "http://???????????????????" | |
val uri = new URI(url) | |
val oauth_params = sign("POST", url, CONSUMER_KEY,CONSUMER_SECRET,GAME_ID) | |
val lis = new ListBuffer[String] | |
oauth_params.foreach((t) => lis + (t._1 + "=\"" + t._2 + "\"")) | |
val auth = """OAuth realm="",""" + lis.mkString(",") | |
val httppost = new HttpPost(uri) | |
val httpclient = new DefaultHttpClient(); | |
val json = "???????????????????????" | |
val reqEntity = new InputStreamEntity( | |
new StringBufferInputStream(json), json.length); | |
reqEntity.setContentType("application/json") | |
httppost.addHeader("Authorization",auth) | |
httppost.setEntity(reqEntity) | |
val response = httpclient.execute(httppost) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment