Scala HTTPS帖子包括JSON输入和输出以及身份验证



我找不到一个Scala HTTPS帖子的例子,包括JSON输入和输出以及身份验证。 我什至在Java中找不到这样的例子。 我可以在 Python 中轻松做到这一点:

def main(user_name, password):
    headers = {'Content-Type': 'application/json', 'Accept': 'application/json'}
    eta_data = """{
      "contact": {
        "longitude": "-151.7200",
        "latitude": "-16.4400",
        "timestamp": "2016-04-22 15:14:55",
        "speedKnots": "15.4"
      },
      "destination": {
        "longitude": "-149.869722",
        "latitude": "-17.491667"
      }
    }"""
    r = requests.post('https://www4.demo.exactearth.com/eta', data=eta_data, auth=(user_name, password), headers=headers)
    print()
    print("eta:")
    print(r.text)
    print(r.json())

不是要求任何人为我将其翻译成 Scala,但这有多难? 有人可以指出我一本涵盖这一点的最新 Scala 书吗? Scala HTTPS post AND JSON 输入和 JSON 输出以及简单的用户名/密码身份验证

在阅读您的问题后,我实际上试图解决此任务。我发现大多数库都非常复杂,并且在其依赖项中使用 Akka。我写了这种调用使用几个库,并且比其他库更喜欢Play-WS。初始化有点长(因为它也使用 Akka(,但实际用法很好,很整洁。

下面是我最终得到的代码。实际调用在call函数中

import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import play.api.libs.ws._
import play.api.libs.ws.ahc._
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits._
object PlayWs extends App{
  val eta_data = """{
      "contact": {
        "longitude": "-151.7200",
        "latitude": "-16.4400",
        "timestamp": "2016-04-22 15:14:55",
        "speedKnots": "15.4"
      },
      "destination": {
        "longitude": "-149.869722",
        "latitude": "-17.491667"
      }
    }"""
  def call(wsClient: StandaloneWSClient): Future[Unit] = {
    wsClient.url("http://requestb.in/ozxfttoz")
      .withAuth("username", "password", WSAuthScheme.BASIC)
      .withHeaders("Content-Type" -> "application/json", "Accept" -> "application/json")
      .post(eta_data).map { response ⇒
        val statusText: String = response.statusText
        println("Response:")
        println(s"${response.status} $statusText")
        println(s"${response.body}")
      }
  }
  // Create Akka system for thread and streaming management
  implicit val system = ActorSystem()
  system.registerOnTermination {
    System.exit(0)
  }
  implicit val materializer = ActorMaterializer()
  val wsClient = StandaloneAhcWSClient()
  call(wsClient)
    .andThen { case _ => wsClient.close() }
    .andThen { case _ => system.terminate() }
}

我使用了独立版本并将其添加到项目中

libraryDependencies += "com.typesafe.play" %% "play-ahc-ws-standalone" % "1.0.0-M6"

Scala 中的 POST、HTTPS、JSON 输入/输出和基本身份验证示例可以在 Akka HTTP 文档中找到,例如:

http://doc.akka.io/docs/akka-http/current/scala/http/client-side/host-level.html

在这里:

http://doc.akka.io/docs/akka-http/current/scala/http/client-side/websocket-support.html

相关内容

最新更新