Post 使用 Akka http 请求
Post request with Akka http
我有这个 post 请求并且有两个问题。
1.is 与 headers
值。文档说它接受一个 Seq[HttpHeader]
并且我传入一个扩展 HttpHeader
的 Seq[RawHeader]
但它说这是一个类型不匹配。为什么?
2.I传入我想要的数据post,但是HttpEntity.Default()
传入一个Source[Bytestring]
。如何将我的 data
转换为 Source[Bytestring]
def post(data: String): Unit = {
val headers = Seq(RawHeader("X-Access-Token", "access token"))
val responseFuture: Future[HttpResponse] =
Http(system).singleRequest(
HttpRequest(
HttpMethods.POST,
"https://beta-legacy-api.ojointernal.com/centaur/user",
headers,
entity = HttpEntity.Default(data)
)
)
}
I pass in a Seq[RawHeader] which extends HttpHeader but it says it's
a type mismatch. Why?
因为Seq[A]
在A
中是不变的。
How do I convert my data to Source[Bytestring]
你不必。您可以使用采用 Array[Byte]
的 HttpEntity
apply 方法,并使用 withHeaders
:
import akka.http.scaladsl.model._
def post(data: String): Unit = {
val responseFuture: Future[HttpResponse] =
Http(system).singleRequest(
HttpRequest(
HttpMethods.POST,
"https://beta-legacy-api.ojointernal.com/centaur/user",
entity = HttpEntity(ContentTypes.`application/json`, data.getBytes())
).withHeaders(RawHeader("X-Access-Token", "access token"))
)
}
我有这个 post 请求并且有两个问题。
1.is 与 headers
值。文档说它接受一个 Seq[HttpHeader]
并且我传入一个扩展 HttpHeader
的 Seq[RawHeader]
但它说这是一个类型不匹配。为什么?
2.I传入我想要的数据post,但是HttpEntity.Default()
传入一个Source[Bytestring]
。如何将我的 data
转换为 Source[Bytestring]
def post(data: String): Unit = {
val headers = Seq(RawHeader("X-Access-Token", "access token"))
val responseFuture: Future[HttpResponse] =
Http(system).singleRequest(
HttpRequest(
HttpMethods.POST,
"https://beta-legacy-api.ojointernal.com/centaur/user",
headers,
entity = HttpEntity.Default(data)
)
)
}
I pass in a Seq[RawHeader] which extends HttpHeader but it says it's a type mismatch. Why?
因为Seq[A]
在A
中是不变的。
How do I convert my data to Source[Bytestring]
你不必。您可以使用采用 Array[Byte]
的 HttpEntity
apply 方法,并使用 withHeaders
:
import akka.http.scaladsl.model._
def post(data: String): Unit = {
val responseFuture: Future[HttpResponse] =
Http(system).singleRequest(
HttpRequest(
HttpMethods.POST,
"https://beta-legacy-api.ojointernal.com/centaur/user",
entity = HttpEntity(ContentTypes.`application/json`, data.getBytes())
).withHeaders(RawHeader("X-Access-Token", "access token"))
)
}