Question

Using the rather simple and elegant Scala Dispatch HTTP library. Since the Twitter Search API is now using OAuth 1.0A, I obviously need to start injecting Consumer and AccessToken information. I've got a simple request below:

val request = url("https://api.twitter.com/1.1/search/tweets.json?q=%23%sresult_type=mixed&count=4" format w.queryValue)
val response = Http(request OK as.String)

What's a way to add headers to this if I already know my Consumer and AccessToken information? The documentation is rather scarce. Thanks!

Was it helpful?

Solution

I'm not familiar with the OAuth API, but Dispatch allows you to add arbitrary HTTP Request headers with the <:< method/operator.

So mashing together your code example above and this "Authorizing a request" example from Twitter's Developer site, you might get something like this:

val authentication = """OAuth oauth_consumer_key="xvz1evFS4wEEPTGEFPHBog", oauth_nonce="kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg",  oauth_signature="tnnArxj06cWHq44gCs1OSKk%2FjLY%3D", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1318622958", oauth_token="370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb", oauth_version="1.0""""

val request = url("https://api.twitter.com/1.1/search/tweets.json?q=%23%sresult_type=mixed&count=4" format w.queryValue)
val authHeader = Map("Authentication" -> authentication) 
val requestWithAuthentication = request <:< authHeader
val response = Http(requestWithAuthentication OK as.String)

I haven't verified whether this actually works, but hopefully it should get you going in the right direction.

OTHER TIPS

I am doing it like this with dispatch:

private def buildSearchReq(searchTerm: String, lat: Double, long: Double): Req = {
  val consumer = new ConsumerKey(consumerKey, consumerSecret)
  val requestToken = new RequestToken(token, tokenSecret)
  val req = url(searchUrl)
    .addQueryParameter("term", searchTerm)
    .addQueryParameter("radius_filter", "40000")
    .addQueryParameter("ll", s"$lat,$long")
  new SigningVerbs(req).sign(consumer, requestToken)
}

You could also do something more like this if you wanted:

private def buildSearchReq(searchTerm: String, lat: Double, long: Double): Req = {
  val req = url(searchUrl) <<? Map("term" -> searchTerm, "radius_filter" -> "40000", "ll" -> s"$lat,$long")
  new SigningVerbs(req).sign(new ConsumerKey(consumerKey, consumerSecret), new RequestToken(token, tokenSecret))
}

There are probably even more terse ways of doing it, but you get the idea.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top