在Scala中执行HTTP请求

问题描述 投票:69回答:9

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

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

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

http scala scalaz
9个回答
116
投票

我使用以下内容: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"

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)

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
投票

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

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

我不一定认为这是最好的选择,但值得一提。


2
投票

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


2
投票

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


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)
  }

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")

0
投票

这是我正在上课的课程。它有GET和POST请求。没有参数的GET - 带参数的POST我用它来与StreamSets通信以启动管道或检查管道状态。

它只需要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"
    }
  }

}

© www.soinside.com 2019 - 2024. All rights reserved.