在Scala中执行HTTP请求

时间:2012-07-30 10:11:03

标签: http scala scalaz

我正在尝试向Web服务发出一个简单的POST请求,该服务在Scala中返回一些XML。

似乎Dispatch是用于此任务的标准库,但我找不到它的文档。我在上面链接的主站点详细解释了什么是承诺以及如何进行异步编程,但实际上并没有记录API。有一个periodic table - 看起来有些可怕 - 但它对那些已经知道该做什么并且只需要提醒一些神秘语法的人来说似乎很有用。

它似乎也是Scalaz has some facility for HTTP,但我也找不到任何文档。

9 个答案:

答案 0 :(得分:115)

我使用以下内容:https://github.com/scalaj/scalaj-http

这是一个简单的GET请求:

import scalaj.http.Http

Http("http://foo.com/search").param("q", "monkeys").asString

以及POST的一个例子:

val result = Http("http://example.com/url").postData("""{"id":"12","json":"data"}""")
  .header("Content-Type", "application/json")
  .header("Charset", "UTF-8")
  .option(HttpOptions.readTimeout(10000)).asString

Scalaj HTTP可通过SBT获得:

libraryDependencies += "org.scalaj" % "scalaj-http_2.11" % "2.3.0"

答案 1 :(得分:6)

您可以使用spray-client。文档缺乏(我花了一些时间来找出how to make GET requests with query parameters)但如果你已经使用喷雾,这是一个很好的选择。文档比发送更好。

我们在AI2超过dispatch时使用它,因为运算符的符号较少,我们已经在使用喷雾/演员。

import spray.client.pipelining._

val url = "http://youruri.com/yo"
val pipeline: HttpRequest => Future[HttpResponse] = sendReceive

// Post with header and parameters
val responseFuture1: Future[String] = pipeline(Post(Uri(url) withParams ("param" -> paramValue), yourPostData) map (_.entity.asString)

// Post with header
val responseFuture2: Future[String] = pipeline(Post(url, yourPostData)) map (_.entity.asString)

答案 2 :(得分:5)

我正在使用发送:http://dispatch.databinder.net/Dispatch.html

他们刚刚发布了一个新版本(0.9.0),其中包含一个我非常喜欢的全新api。它是异步的。

项目页面示例:

import dispatch._
val svc = url("http://api.hostip.info/country.php")
val country = Http(svc OK as.String)

for (c <- country)
  println(c)

编辑:这可能对您有所帮助https://github.com/dispatch/reboot/blob/master/core/src/main/scala/requests.scala

答案 3 :(得分:3)

另一种选择是Typesafe的play-ws,它是作为独立库分类的Play Framework WS库:

http://blog.devalias.net/post/89810672067/play-framework-seperated-ws-library

我不一定会将此作为最佳选择,但值得一提。

答案 4 :(得分:2)

为什么不使用Apache HttpComponents?这是application FAQ,涵盖了各种各样的场景。

答案 5 :(得分:2)

如果我可以创建一个无耻的插件,我有一个名为Bee-Client的API,它只是Scala for Java的HttpUrlConnection的包装器。

答案 6 :(得分:1)

我必须做同样的事情来测试一个终点(在Integration测试中)。以下是在Scala中从GET请求获取响应的代码。 我正在利用scala.io.Source从端点和ObjectMapper读取json到对象的转换。

private def buildStockMasterUrl(url:String, stockStatus:Option[String]) = {
      stockStatus match  {
        case Some(stockStatus) => s"$url?stockStatus=${stockStatus}"
        case _ => url
    }
  }

    private def fetchBooksMasterData(stockStatus:Option[String]):  util.ArrayList[BooksMasterData] = {
    val url: String = buildBooksMasterUrl("http://localhost:8090/books/rest/catalogue/booksMasterData",stockStatus)
    val booksMasterJson : String = scala.io.Source.fromURL(url).mkString
    val mapper = new ObjectMapper()
    apper.readValue(booksMasterJson,classOf[util.ArrayList[BooksMasterData]])
}

case class BooksMasterData(id:String,description: String,category: String)

这是我对同一个

的测试方法
test("validate booksMasterData resource") {
    val booksMasterData = fetchBooksMasterData(Option(null))
    booksMasterData.size should be (740)
  }

答案 7 :(得分:1)

使用我的Requests-Scala库:

// Mill
ivy"com.lihaoyi::requests:0.1.8"
// SBT
"com.lihaoyi" %% "requests" % "0.1.8"

这很简单

val r = requests.get("https://api.github.com/users/lihaoyi")

r.statusCode
// 200

r.headers("content-type")
// Buffer("application/json; charset=utf-8")

r.text
// {"login":"lihaoyi","id":934140,"node_id":"MDQ6VXNlcjkzNDE0MA==",...
val r = requests.post("http://httpbin.org/post", data = Map("key" -> "value"))

val r = requests.put("http://httpbin.org/put", data = Map("key" -> "value"))

val r = requests.delete("http://httpbin.org/delete")

val r = requests.head("http://httpbin.org/head")

val r = requests.options("http://httpbin.org/get")

答案 8 :(得分:0)

这是我正在上的课。它同时具有GET和POST请求。 不带参数的GET-带参数的POST 我使用它与StreamSet进行通信,以启动管道或检查管道状态。

在build.sbt文件中只需要以下依赖项:

libraryDependencies += "org.scalaj" %% "scalaj-http" % "2.3.0"

您可以在此处找到文档:https://github.com/scalaj/scalaj-http#post-raw-arraybyte-or-string-data-and-get-response-code


import scala.collection.mutable.ArrayBuffer
import scalaj.http.{Http, HttpResponse}

object HttpRequestHandler {

  val userName: String = "admin"
  val password: String = "admin"

  def sendHttpGetRequest(request: String): String = {

    println(" Send Http Get Request (Start) ")

    try {

      val httpResponse: HttpResponse[String] = Http(request).auth(userName,password)
                                                            .asString

      val response = if (httpResponse.code == 200) httpResponse.body
      else{
        println("Bad HTTP response: code = "+httpResponse.code )
        return "ERROR"
      }

      println(" Send Http Get Request (End) ")

      return response

    } catch {
      case e: Exception => println("Error in sending Get request: "+e.getMessage)
        return "ERROR"
    }


  }

  def arrayBufferToJson(params:ArrayBuffer[(String,String)]): String ={

    var jsonString = "{"
    var count: Int = 0
    for(param <- params){
      jsonString+="\""+param._1+"\":\""+param._2+"\""+ ( if(count!=params.length-1) "," else "")
      count+=1
    }
    jsonString+="}"

    return jsonString

  }

  def sendHttpPostRequest(request: String,params: ArrayBuffer[(String,String)]): String = {

    println(" Send Http Post Request (Start) ")

    try {
      val postData : String = arrayBufferToJson(params)
      println("Parameters: "+postData)
      val httpResponse: HttpResponse[String] = Http(request).auth(userName,password)
                                                            .header("X-Requested-By","sdc")
                                                            .header("Content-Type", "application/json;charset=UTF-8")
                                                            .header("X-Stream" , "true")
                                                            .header("Accept", "application/json")
                                                            .postData(postData.getBytes)
                                                            .asString


      val response = if (httpResponse.code == 200) httpResponse.body
      else{
        println("Bad HTTP response: code = "+httpResponse.code )
        "ERROR"
      }

      println(" Send Http Post Request (End) ")

      return response

    } catch {
      case e: Exception => println("Error in sending Post request: " + e.getMessage)
        return "ERROR"
    }
  }

}