6

In Finagle, how do I create a request an HTTP GET request with parameters in a safe, clean way?

val request = RequestBuilder()
  .url("http://www.example.com/test")
  .addParameter("key", "value")   // this doesn't exist
  .buildGet()
request    // should be a GET request for http://www.example.com/test?key=value
duckworthd
  • 14,679
  • 16
  • 53
  • 68

3 Answers3

10

You can use the confusingly-named Request.queryString:

val request = RequestBuilder()
  .url(Request.queryString("http://www.example.com/test", Map("key" -> "value"))
  .buildGet()
Robin Green
  • 32,079
  • 16
  • 104
  • 187
2

The arguments passed to RequestBuilder.url() are expected to be fully-formed, so Finagle doesn't provide any way to tack on more query parameters.

One way to solve this would be to construct a URL object outside of the context of the RequestBuilder chain. You could define your query parameters in a Map, turn it into a query string, and then concatenate it to the base URL:

val paramStr = Map("key" -> "value", ...) map { case (k, v) =>
  k + '=' + v
} mkString("?", "&", "")

val request = RequestBuilder.safeBuildGet(
  RequestBuilder.create()
    .url("http://www.example.com/test" + paramsStr)
)

Note that you'll need to encode any query parameters that you specify in the Map.

Evan Meagher
  • 4,517
  • 21
  • 18
-1

You can safely create your request by this way:

import java.net.URL
import com.twitter.finagle.http.{Http, RequestBuilder}

val request = RequestBuilder()
             .url(new URL("http://www.example.com/test?key=value"))
             .setHeader("Content-Type", "application/json") //if you need
             .buildGet()