Scala를위한 간단하고 간결한 HTTP 클라이언트 라이브러리
스칼라에 관용적이며 사용법이 간결하며 단순한 의미 체계가있는 성숙한 HTTP 클라이언트 라이브러리가 필요합니다. 나는 Apache HTTP와 Scala Dispatch와 관용적 인 Scala 래핑을 약속하는 수많은 새로운 라이브러리를 살펴 보았습니다. Apache HTTP 클라이언트는 확실히 자세한 정보를 요구하지만 Dispatch는 쉽게 혼란 스러웠습니다.
Scala 사용에 적합한 HTTP 클라이언트는 무엇입니까?
나는 최근 에 약간 난해한 Dispatch를 사용하기 시작했습니다 (대단한 일반 소개, 자세한 시나리오 / 사용 사례 기반 문서의 심각한 부족). Dispatch 0.9.1은 Ning의 Async Http Client를 둘러싼 Scala 래퍼입니다 . 무슨 일이 일어나고 있는지 완전히 이해하려면 도서관에 자신을 소개해야합니다. 실제로 내가 실제로 살펴 봐야 할 유일한 것은 RequestBuilder 였습니다. 그 밖의 모든 것은 HTTP에 대한 이해에 잘 맞았습니다 .
나는 0.9 릴리스에서 작업을 매우 간단하게 완료하는 것에 대해 (지금까지!) 단호한 엄지 손가락을주었습니다. 일단 초기 학습 곡선을 통과하면.
Dispatch의 Http "builder"는 변경 불가능하며 스레드 환경에서 잘 작동하는 것 같습니다. 비록 스레드로부터 안전하다는 것을 문서에서 찾을 수는 없지만; 소스에 대한 일반적인 독서는 그것이 있음을 시사합니다.
알고 있어야 함 RequestBuilder 의이 변경할 수 있으며, 따라서 스레드 안전하지 않습니다.
도움이되는 추가 링크는 다음과 같습니다.
0.9. * 릴리스에 대한 ScalaDoc 링크를 찾을 수 없으므로 0.9. * 릴리스에 대한 소스 코드를 검색합니다 .
0.8 릴리스 용 ScalaDoc ; 실질적으로 0.9 다른 짐승 (오늘).
또한 0.8 관련 연산자 의 "주기적"표 .
이전 0.8 "dispatch-classic"문서 는 그들이 URL 작성기를 사용하는 방법을 이해하는 데 도움이되었으며, 0.9로 이월 한 것들이 어떻게 연결되는지에 대한 힌트를 제공했습니다.
나는 한 대부분의 주요 HTTP 클라이언트의 비교가 가능한 도서관
Dispatch 및 기타 일부 라이브러리 는 더 이상 유지되지 않습니다 . 현재 유일한 진지한 것은 스프레이 클라이언트 와 플레이! WS .
spray-client 는 구문에서 약간 난해합니다. play-ws 는 사용하기 매우 쉽습니다.
(build.sbt)
libraryDependencies += "com.typesafe.play" %% "play-ws" % "2.4.3"
(기본 사용법)
val wsClient = NingWSClient()
wsClient
.url("http://wwww.something.com")
.get()
.map { wsResponse =>
// read the response
}
여기 파티에 조금 늦었지만 spray-client에 깊은 인상을 받았습니다 .
요청을 작성하기위한 멋진 DSL이 있고 동기화 및 비동기 실행을 모두 지원할뿐만 아니라 다양한 (un) 마샬링 유형 (JSON, XML, 양식)을 지원합니다. Akka 와도 아주 잘 어울립니다 .
두
식스 년이 처음에이 소식에 응답 한 후, 나는 다른 대답을 할 것이다.
저는 스프레이와 akka 팀 간의 협력 인 akka-http를 사용 하고 있습니다. Lightbend의 지원을받으며 akka 비동기 환경과 밀접하게 연계되어 있습니다.이 작업에 적합한 도구입니다.
아파치 클라이언트에 대해 불행한 경험이 있었기 때문에 나는 직접 작성하기 시작했습니다. 기본 제공 HttpURLConnection은 버그가 있다고 널리 주장됩니다. 그러나 그것은 나의 경험이 아닙니다. 사실, 그 반대의 경우, 아파치 클라이언트는 다소 문제가있는 스레딩 모델을 가지고 있습니다. Java6 (또는 5?) 이후 HttpURLConnection은 Keep-alive와 같은 필수 기능이 내장 된 효율적인 HTTP1.1 연결을 제공했으며 번거 로움없이 동시 사용을 처리합니다.
그래서 HttpURLConnection에서 제공하는 불편한 API를 보완하기 위해 Scala에서 새로운 API를 오픈 소스 프로젝트로 작성하기로했습니다. HttpURLConnection의 래퍼 일 뿐이지 만 HttpURLConnection과 달리 사용하기 쉽습니다. Apache 클라이언트와 달리 기존 프로젝트에 쉽게 맞아야합니다. Dispatch와 달리 배우기 쉬울 것입니다.
Bee Client라고합니다.
- 웹 사이트 : http://www.bigbeeconsultants.co.uk/bee-client
- API 문서 : http://www.bigbeeconsultants.co.uk/docs/bee-client/latest.html
뻔뻔한 플러그에 대해 사과드립니다. :)
sttp 는 우리 모두가 기다려온 Scala HTTP 라이브러리입니다!
요청을 형성하고 실행하기위한 유창한 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)
Akka-HTTP (이전의 Spray) 및 유서 깊은 AsyncHttpClient (Netty)를 포함한 플러그 형 백엔드를 통해 동기식, 비동기식 및 스트리밍 호출을 지원합니다.
implicit val sttpHandler = AsyncHttpClientFutureHandler()
val futureFirstResponse: Future[Response[String]] = request.send()
그것은 지원 scala.concurrent.Future
, scalaz.concurrent.Task
, monix.eval.Task
,와 cats.effect.IO
- 모든 주요 스칼라 IO는 라이브러리를 모나드.
또한 소매에 몇 가지 추가 트릭이 있습니다.
요청과 응답 모두에 대한 케이스 클래스 표현이 있습니다 (강력하게 형식화 된 헤더가있는 만큼은 아니지만) : https://github.com/softwaremill/sttp/blob/master/core/src/main/scala /com/softwaremill/sttp/RequestT.scala https://github.com/softwaremill/sttp/blob/master/core/src/main/scala/com/softwaremill/sttp/Response.scala
URI 문자열 보간기를 제공합니다 .
val test = "chrabąszcz majowy" val testUri: Uri = uri"http://httpbin.org/get?bug=$test"
- 요청 본문 / 응답을위한 인코더 / 디코더 (예 : Circe를 통한 JSON)를 지원합니다.
import com.softwaremill.sttp.circe._ val response: Either[io.circe.Error, Response] = sttp .post(uri"...") .body(requestPayload) .response(asJson[Response]) .send()
마지막으로 Softwaremill의 신뢰할 수있는 사람들이 유지 관리하며 훌륭한 문서가 있습니다.
디스패치 외에는 많지 않습니다. scalaz 는 기능적인 http 클라이언트를 구축하려고했습니다. 그러나 그것은 scalaz7 브랜치에 그것의 버전이 존재하지 않는 한동안 구식입니다. 또한 playframework 내에 ning async-http-client 의 유용한 래퍼 가 있습니다. 거기에서 다음과 같은 전화를 할 수 있습니다.
WS.url("http://example.com/feed").get()
WS.url("http://example.com/item").post("content")
플레이를 사용하지 않으면이 API를 영감으로 사용할 수 있습니다! 프로젝트에서 Dispatch API를 싫어합니다.
스프레이
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 akka actor library, which is extremely scalable and powerful. You can scale out your http client to several machines by only changing conf
files.
Moreover few month ago Spray join Typesafe, and as I understand it will become a part of the basic akka distribution. proof
Play2
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.
ScalaJ-Http is a very simple synchronous http client
https://github.com/scalaj/scalaj-http
I'd recommend it if you need a no-ceremony barebones Scala client.
I've used Dispatch, Spray Client and the Play WS Client Library...None of them were simply to use or configure. So I created a simpler HTTP Client library which lets you perform all the classic HTTP requests in simple one-liners.
See an example:
import cirrus.clients.BasicHTTP.GET
import scala.concurrent.Await
import scala.concurrent.duration._
object MinimalExample extends App {
val html = Await.result(Cirrus(GET("https://www.google.co.uk")), 3 seconds)
println(html)
}
... produces ...
<!doctype html><html itemscope="" itemtype="http://schema.org/WebPage" lang="en-GB">...</html>
The library is called Cirrus and is available via Maven Central
libraryDependencies += "com.github.godis" % "cirrus_2.11" % "1.4.1"
The documentation is available on GitHub
https://github.com/Godis/Cirrus
Surprised that no one mentioned finagle here. It is super simple to use:
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
참고URL : https://stackoverflow.com/questions/12334476/simple-and-concise-http-client-library-for-scala
'Program Tip' 카테고리의 다른 글
git이 특정 반환 오류 코드를 반환합니까? (0) | 2020.10.19 |
---|---|
C #의 제네릭-인수를 사용하여 변수 유형의 인스턴스를 어떻게 만들 수 있습니까? (0) | 2020.10.19 |
Mac OS X에서 대용량 파일 편집 (0) | 2020.10.18 |
.NET 위임 유형에 대한 적절한 명명 규칙? (0) | 2020.10.18 |
Java에서 클래스 속성을 반복하는 방법은 무엇입니까? (0) | 2020.10.18 |