繁体   English   中英

使用scala中的dispatch访问Rdio oauth API时出错

[英]Error when accessing Rdio oauth API with dispatch in scala

我正在尝试使用scala dispatch来访问Rdio API,如下所示:

import dispatch.url
import dispatch.Http
import dispatch.Defaults.executor
import dispatch._
import com.ning.http.client.oauth.ConsumerKey
import dispatch.oauth._

val consumer = new ConsumerKey("my key", "my secret")
val params = Map("method" -> "get", "keys" -> id, "extras" -> "-*,playCount")
val request = url("http://api.rdio.com/1/").POST <@ consumer << params <:< Map("Accept" -> "application/json")
val response = Http(request OK as.String)

我收到错误403。

怎么了? 我确信我的钥匙是正确的。

我已经分析了rdio页面上的python示例和Scala的作用之间的区别。

我认为确实存在两个问题。

  1. 首先,您需要获取访问令牌。

  2. 第二个问题是,调度库的符号方法显然使rdio不满意。 它删除尾部斜杠,这使得签名不匹配。

第一个问题很容易解决 - 您只需要使用Exchange类,它将为您完成大部分工作。

第二个问题非常棘手,我刚刚复制了原始的sign方法并更改了部分,这是删除了一个尾部斜杠。

代码如下。

val ck = new ConsumerKey("YOUR_CONSUMER_KEY", "YOUR_CONSUMER_TOKEN")

// declare exchange to obtain an access token
val exchange = new Exchange with SomeHttp with SomeCallback with SomeConsumer with SomeEndpoints {

  override def http: HttpExecutor = Http

  override def callback: String = "oob"

  override def consumer: ConsumerKey = ck

  override def accessToken: String = "http://api.rdio.com/oauth/access_token"

  override def authorize: String = "http://api.rdio.com/oauth/authorize"

  override def requestToken: String = "http://api.rdio.com/oauth/request_token"
}

/// we change the default method of the dispatch
def sign(request: Req, consumer: ConsumerKey, token: RequestToken): Req = {
  val calc = new OAuthSignatureCalculator(consumer, token)
  request underlying { r =>
    val req = r.build
    //!!! here we make change so the trailing slash is not removed
    val baseurl = req.getURI.toString.takeWhile(_ != '?').mkString("")
    calc.calculateAndAddSignature(baseurl, req, r)
    r
  }
}

val response = exchange.fetchRequestToken.right.flatMap { rt =>

  // point your browser to this URL with the given oauth token, we'll get PIN back
  println(s"Go to https://www.rdio.com/oauth/authorize/?oauth_callback=oob&oauth_token=${rt.getKey}")
  print("Enter PIN:")
  val pin = readLine()

  exchange.fetchAccessToken(rt, pin)
}.right.flatMap { at =>
  // now we can call API using the consumer key and the access token
  val request = sign(url("http://api.rdio.com/1/").POST << Map("method" -> "currentUser"), ck, at)
  val response = Http(request > as.String)
  response.map(Right(_))
}

response.map { responseOrError =>
  responseOrError.fold(err => println(s"Error $err"), suc => println(s"Response: $suc"))
  Http.shutdown()
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM