Scala 的简单简洁的 HTTP 客户端库

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12334476/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 04:30:21  来源:igfitidea点击:

Simple and concise HTTP client library for Scala

scalahttp

提问by Jesvin Jose

I need a mature HTTP client library that is idiomatic to scala, concise in usage, simple semantics. I looked at the Apache HTTP and the Scala Dispatch and numerous new libraries that promise an idiomatic Scala wrapping. Apache HTTP client sure demands verbosity, while Dispatch was easily confusing.

我需要一个成熟的 HTTP 客户端库,它是 Scala 惯用的,使用简洁,语义简单。我查看了 Apache HTTP 和 Scala Dispatch 以及许多承诺使用惯用 Scala 包装的新库。Apache HTTP 客户端肯定要求冗长,而 Dispatch 很容易混淆。

What is a suitable HTTP client for Scala usage?

什么是适合 Scala 使用的 HTTP 客户端?

采纳答案by Richard Sitze

I've recently started using Dispatch, a bit arcane (great general intro, serious lack of detailed scenario/use-case based docs). Dispatch 0.9.1 is a Scala wrapper around Ning's Async Http Client; to fully understand what going on requires introducing one's self to that library. In practice, the only thing I really had to look at was the RequestBuilder- everything else falling nicely into my understanding of HTTP.

我最近开始使用Dispatch,有点神秘(很好的一般介绍,严重缺乏基于详细场景/用例的文档)。Dispatch 0.9.1 是围绕 Ning 的Async Http Client的 Scala 包装器;要完全理解正在发生的事情,需要将自己介绍给那个图书馆。在实践中,我唯一真正需要看的是RequestBuilder- 其他一切都很好地融入了我对 HTTP 的理解。

I give the 0.9 release a solid thumbs up (so far!) on getting the job done very simply.. once you get past that initial learning curve.

我给 0.9 版本一个坚实的大拇指(到目前为止!)在非常简单地完成工作方面......一旦你通过了最初的学习曲线。

Dispatch's Http "builder" is immutable, and seems to work well in a threaded environment. Though I can't find anything in docs to state that it is thread-safe; general reading of source suggests that it is.

Dispatch 的 Http “builder” 是不可变的,并且似乎在线程环境中运行良好。虽然我在文档中找不到任何说明它是线程安全的;对来源的一般阅读表明它是。

Do be aware that the RequestBuilder's are mutable, and therefore are NOT thread-safe.

请注意RequestBuilder是可变的,因此不是线程安全的。

Here are some additional links I've found helpful:

以下是我发现有帮助的一些其他链接:

回答by implicitdef

I did a comparison of most major HTTP client libraries available

对大多数可用的主要 HTTP 客户端库进行了比较

Dispatch, and a few others libraries, are not maintained anymore. The only serious ones currently are spray-clientand Play! WS.

Dispatch 和其他一些库不再维护。目前唯一认真的就是spray-clientPlay!WS

spray-clientis a bit arcane in its syntax. play-wsis quite easy to use :

Spray-client的语法有点神秘。play-ws很容易使用:

(build.sbt)

(build.sbt)

libraryDependencies += "com.typesafe.play" %% "play-ws" % "2.4.3"

(basic usage)

(基本用法)

val wsClient = NingWSClient()
wsClient
  .url("http://wwww.something.com")
  .get()
  .map { wsResponse =>
    // read the response
}

回答by Mark Tye

A little late to the party here, but I've been impressed with spray-client.

这里的聚会有点晚了,但我对Spray-client印象深刻。

It's got a nice DSL for building requests, supports both sync and async execution, as well as a variety of (un)marshalling types (JSON, XML, forms). It plays very nicely with Akka, too.

它有一个很好的 DSL 来构建请求,支持同步和异步执行,以及各种(非)编组类型(JSON、XML、表单)。它也与Akka配合得很好。

回答by Richard Sitze

TwoSix years after originally responding to this post, I would have a different answer.

在最初回复这篇文章两年六年后,我会有不同的答案。

I've been using akka-http, a collaboration between the spray and akka teams. It's backed by Lightbend, tightly aligned with the akka async environment... it's the right tool for this job.

我一直在使用akka-http,这是 Spray 和 akka 团队之间的合作。它由 Lightbend 提供支持,与 akka 异步环境紧密结合......这是完成这项工作的正确工具。

回答by Rick-777

Having had some unhappy experiences with the Apache client, I set about writing my own. The built-in HttpURLConnection is widely asserted to be buggy. But that's not my experience of it. In fact, the reverse has been so, the Apache client having a somewhat problematic threading model. Since Java6 (or 5?), HttpURLConnection has provided efficient HTTP1.1 connections with essentials like keep-alive being built in, and it handles concurrent usage without fuss.

在使用 Apache 客户端有一些不愉快的经历后,我开始编写自己的客户端。内置的 HttpURLConnection 被广泛认为是有缺陷的。但这不是我的经验。事实上,情况正好相反,Apache 客户端的线程模型有些问题。从 Java6(或 5?)开始,HttpURLConnection 提供了高效的 HTTP1.1 连接,其中内置了 keep-alive 等基本功能,并且可以毫不费力地处理并发使用。

So, to compensate for the inconvenient API offered by HttpURLConnection, I set about writing a new API in Scala, as an open-source project. It's just a wrapper for HttpURLConnection, but unlike HttpURLConnection, it aims to be easy to use. Unlike Apache client, it should fit easily into an existing project. Unlike Dispatch, it should be easy to learn.

因此,为了弥补 HttpURLConnection 提供的不方便的 API,我开始在 Scala 中编写一个新的 API,作为一个开源项目。它只是 HttpURLConnection 的包装器,但与 HttpURLConnection 不同的是,它旨在易于使用。与 Apache 客户端不同,它应该很容易融入现有项目。与 Dispatch 不同,它应该很容易学习。

It's called Bee Client

它被称为蜜蜂客户端

My apologies for the shameless plug. :)

我为无耻的插头道歉。:)

回答by tksfz

sttpis the Scala HTTP library we've all been waiting for!

sttp是我们一直在等待的 Scala HTTP 库!

It has a fluent DSL for forming and executing requests (code samples from their README):

它具有用于形成和执行请求的流畅 DSL(来自其 README 的代码示例):

val request = sttp
  .cookie("session", "*!@#!@!$")
  .body(file) // of type java.io.File
  .put(uri"http://httpbin.org/put")
  .auth.basic("me", "1234")
  .header("Custom-Header", "Custom-Value")
  .response(asByteArray)

It supports synchronous, asynchronous, and streaming calls via pluggable backends, including Akka-HTTP (formerly Spray) and the venerable AsyncHttpClient (Netty):

它通过可插拔的后端支持同步、异步和流调用,包括 Akka-HTTP(以前的 Spray)和古老的 AsyncHttpClient(Netty):

implicit val sttpHandler = AsyncHttpClientFutureHandler()
val futureFirstResponse: Future[Response[String]] = request.send()

It supports scala.concurrent.Future, scalaz.concurrent.Task, monix.eval.Task, and cats.effect.IO- all the major Scala IO monad libraries.

它支持scala.concurrent.Futurescalaz.concurrent.Taskmonix.eval.Taskcats.effect.IO- 所有主要的 Scala IO monad 库。

Plus it has a few additional tricks up its sleeve:

此外,它还有一些额外的技巧:

val test = "chrab?szcz majowy" val testUri: Uri = uri"http://httpbin.org/get?bug=$test"

val test = "chrab?szcz majowy" val testUri: Uri = uri"http://httpbin.org/get?bug=$test"

  • It supports encoders/decoders for request bodies/responses e.g. JSON via Circe:
  • 它支持请求正文/响应的编码器/解码器,例如通过 Circe 的 JSON:

import com.softwaremill.sttp.circe._ val response: Either[io.circe.Error, Response] = sttp .post(uri"...") .body(requestPayload) .response(asJson[Response]) .send()

import com.softwaremill.sttp.circe._ val response: Either[io.circe.Error, Response] = sttp .post(uri"...") .body(requestPayload) .response(asJson[Response]) .send()

Finally, it's maintained by the reliable folks at softwaremill and it's got great documentation.

最后,它由 softwaremill 的可靠人员维护,并且有很好的文档

回答by opeth

Besides Dispatch there is not much out there. scalazhad a attempt at building a functional http client. But it is outdated for a while an no version of it exists in the scalaz7 branch. Additionally there is a useful wrapperof the ning async-http-client within the playframework. There your can do calls like:

除了 Dispatch 之外,没有太多东西。scalaz尝试构建一个功能性的 http 客户端。但是它已经过时了一段时间,scalaz7 分支中不存在它的版本。此外,在 playframework 中还有一个有用的 ning async-http-client包装器。在那里你可以打电话:

WS.url("http://example.com/feed").get()
WS.url("http://example.com/item").post("content")

You can use this API as inspiration if you don't use play! in your project and dislike the Dispatch API.

如果你不玩玩,你可以使用这个 API 作为灵感!在您的项目中并且不喜欢 Dispatch API。

回答by Alex Povar

Spray

You really should consider using Spray. In my opinion it has a bit of tricky syntax, but it is still pretty usable if you aim to build a high-performance http client. The main advantage of using Spray is that it is based on the akkaactor library, which is extremely scalable and powerful. You can scale out your http client to several machines by only changing conffiles.

你真的应该考虑使用Spray。在我看来,它的语法有点棘手,但如果您打算构建一个高性能的 http 客户端,它仍然非常有用。使用 Spray 的主要优点是它基于akkaactor 库,具有极强的可扩展性和强大的功能。您可以仅通过更改conf文件将 http 客户端扩展到多台机器。

Moreover few month ago Spray join Typesafe, and as I understand it will become a part of the basic akka distribution. proof

此外,几个月前 Spray 加入了 Typesafe,据我所知,它将成为基本 akka 发行版的一部分。证明

Play2

播放2

Another option is the Play2 WS lib usage (doc). As far as I know it is still not separated from the Play distribution, but due to its extremely simplicity it is worth it to spend some time attaching the whole Play framework to get that part. There are some issues with providing configuration to it, so this is not great for drop-and-use cases. However, we have used it in few non Play-based projects and everything was fine.

另一种选择是 Play2 WS lib 用法 ( doc)。据我所知,它仍然没有与 Play 发行版分开,但由于它极其简单,花一些时间附加整个 Play 框架来获得那部分是值得的。为其提供配置存在一些问题,因此这对于丢弃和使用案例来说不是很好。然而,我们在几个非基于 Play 的项目中使用了它,一切都很好。

回答by tdmadeeasy

ScalaJ-Http is a very simple synchronous http client

ScalaJ-Http 是一个非常简单的同步 http 客户端

https://github.com/scalaj/scalaj-http

https://github.com/scalaj/scalaj-http

I'd recommend it if you need a no-ceremony barebones Scala client.

如果您需要一个简单的准系统 Scala 客户端,我会推荐它。

回答by Yuchen Zhong

Surprised that no one mentioned finagle here. It is super simple to use:

令人惊讶的是,这里没有人提到 fingle。使用起来超级简单:

import com.twitter.finagle.{Http, Service}
import com.twitter.finagle.http
import com.twitter.util.{Await, Future}

object Client extends App {
  val client: Service[http.Request, http.Response] = Http.newService("www.scala-lang.org:80")
  val request = http.Request(http.Method.Get, "/")
  request.host = "www.scala-lang.org"
  val response: Future[http.Response] = client(request)
  Await.result(response.onSuccess { rep: http.Response =>
    println("GET success: " + rep)
  })
}

See quick start guid for more detail: https://twitter.github.io/finagle/guide/Quickstart.html

有关更多详细信息,请参阅快速入门指南:https: //twitter.github.io/finagle/guide/Quickstart.html