我正在使用akka-http处理get请求,我想转发到同一主机,但更改了以下参数:
- 将GET转换为POST
- 将端口从
8080
更改为8081
- 删除参数并发送一个JSON。我已经创建了要发送的JSON值。
我查阅了这个页面和这个answer。我正在使用extract(_.request) { request =>
提取请求,然后使用StatusCodes.MovedPermanently
创建一个redirect(
。
val routes: Route = {
get {
(path(IntNumber) & parameterSeq) { (adId: Int, params: Seq[(String, String)]) =>
// handling requests as: "http://localhost:8080/2?c=5&b=2", make sure to use the request between quotes
println(s"The ad ID: $adId contains the parameters: ${params.map(paramString).mkString(", ")}")
val bid = getBid(adId, params)
println(s"bid request: ${bid.toJson.prettyPrint}")
// HOW TO REDIRECT TO ANOTHER PORT, CHANGE THE METHOD FROM GET TO POST, AND SEND A JSON PAYLOAD?
val newRequest = HttpRequest(
HttpMethods.POST,
uri = "/",
entity = HttpEntity(ContentTypes.`application/json`, bid.toJson.toString)
)
redirect(
newRequest
.uri
.withHost("localhost")
.withPort(8082),
StatusCodes.MovedPermanently
)
// complete(StatusCodes.OK)
} ~ pathEndOrSingleSlash {
complete(StatusCodes.BadRequest)
} ~ {
complete(StatusCodes.Forbidden)
}
}
}
但是当我向akka-http应用程序$ http GET "localhost:8080/3?b=5&c=10&d=19&c=10"
发送get时,端口8082
上的服务器没有应答。
$ http GET "localhost:8080/3?b=5&c=10&d=19&c=10"
HTTP/1.1 301 Moved Permanently
Content-Length: 92
Content-Type: text/html; charset=UTF-8
Date: Fri, 19 Feb 2021 15:49:21 GMT
Location: //localhost:8082/
Server: akka-http/10.2.2
This and all future requests should be directed to <a href="//localhost:8082/">this URI</a>.
为了测试服务器是否在工作,我可以发送POST
请求,然后收到应答:
$ http POST localhost:8082 < src/main/resources/bidders-request-10.json
HTTP/1.1 200 OK
Content-Type: application/json;charset=UTF-8
Date: Fri, 19 Feb 2021 15:51:02 GMT
Server: Apache-Coyote/1.1
Transfer-Encoding: chunked
{
"bid": 0,
"content": "b:$price$",
"id": "10"
}
1条答案
按热度按时间cvxl0en21#
因此,我通过创建一个执行
Http().singleRequest(HttpRequest(uri = "https://akka.io"))
的参与者来解决这个问题,就像这个例子一样。我的工作解决方案是:我只是不知道如何使Spray JSON不使用
[
和]
。然后我用.replace("[[", "{")
做了那个讨厌的对话。但是,解决方案已经工作了。Spray JSON我正在寻找一个更好的方法来转换它。我猜有另一种形式来创建case类,不使用[
和]
。