2

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!

Urist McDev
  • 498
  • 3
  • 14
crockpotveggies
  • 12,682
  • 12
  • 70
  • 140

2 Answers2

1

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.

Mark Tye
  • 1,661
  • 16
  • 10
  • Credit where credit is due: http://stackoverflow.com/questions/1394667/setting-user-agent-header-in-scala-with-databinders-dispatch-library is what reminded me about the `<:<` operator. – Mark Tye Aug 06 '13 at 19:56
0

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.

smashedtoatoms
  • 1,648
  • 14
  • 19