我找不到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发布和JSON输入和JSON输出以及简单的用户名/密码认证
答案 0 :(得分:3)
我在阅读你的问题后,实际上试图解决这个问题。我发现大多数库都非常复杂,并且在它们的依赖项中使用了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"
答案 1 :(得分:0)
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