如何从Akka HTTP POST请求读取JSON正文并将最终响应作为JSON数组发送

嫩脚

我是akka http的新手。我创建了一个程序来使用http发出发布请求,如下所示-

object MainController {


  def main(args: Array[String]) {
    implicit val system = ActorSystem()
    implicit val materializer = ActorMaterializer()
    implicit val executionContext = system.dispatcher

    val serverSource = Http().bind(interface = "localhost", port = 9000)

    val requestHandler: HttpRequest => HttpResponse = {
      case HttpRequest(GET, Uri.Path("/welcome"), _, _, _) =>
        HttpResponse(entity = HttpEntity(
          ContentTypes.`text/html(UTF-8)`,
          "<html><body>Welcome to API Application</body></html>"))


      case HttpRequest(POST, Uri.Path("/parseData"), _, entity: HttpEntity, _) =>

// Here Need to read request body which is in json format
        println("1 " + new String(entity.getDataBytes()))
        println("2 " + entity.getDataBytes())
// here need to do some calculations and again construct array of json response and send as HttpResponse
        HttpResponse(entity = "PONG!")

      case r: HttpRequest =>
        r.discardEntityBytes() // important to drain incoming HTTP Entity stream
        HttpResponse(404, entity = "Unknown resource!")
    }

    val bindingFuture = Http().bindAndHandleSync(requestHandler, "localhost", 9000)
    println(s"Server online at http://localhost:8080/\nPress RETURN to stop...")
    StdIn.readLine() // let it run until user presses return
    bindingFuture
      .flatMap(_.unbind()) // trigger unbinding from the port
      .onComplete(_ => system.terminate()) // and shutdown when done

  }
}

正如我在“ Post”请求中的上述代码中提到的那样,我需要读取请求主体数据(它是json数组)并进行一些计算,最后将已处理的json数组发送到HTTPResponse。甚至尝试了高级API,但它再次陷入编组中。任何人都可以在这方面解释或帮助我。

我尝试了以下另一种方法-

object MainController {

  // needed to run the route
  implicit val system = ActorSystem()
  implicit val materializer = ActorMaterializer()
  implicit val executionContext = system.dispatcher

  final case class hexRecord(hexstring: String)
  final case class DeviceData(hexData: List[hexRecord])
  // formats for unmarshalling and marshalling

  implicit val contentFormat = jsonFormat1(hexRecord)
  implicit val dataFormat = jsonFormat1(DeviceData)

  def main(args: Array[String]) {

    implicit val formats = org.json4s.DefaultFormats

    val requestBody = List.empty[Map[String, Any]]
    val route: Route =
      concat(
        get {
          path("welcome"){
          complete("Welcome to Parsing Application")}
        },
        post {
          path("parseDeviceData") {
            entity(as[DeviceData]) { data => {
              val result = data.hexData.map(row => {
                val parseData = ParserManager(Hex.decodeHex(row.hexstring.replaceAll("\\s", "").toCharArray))
               val jsonString = Serialization.writePretty(parseData)
                jsonString

              }).toArray 

              complete(result)
            }
            }
          }
        }
      )

    val bindingFuture = Http().bindAndHandle(route, "localhost", 9000)
    println(s"Server online at http://localhost:9000/")
    StdIn.readLine() // let it run until user presses return
    bindingFuture
      .flatMap(_.unbind()) // trigger unbinding from the port
      .onComplete(_ => system.terminate()) // and shutdown when done
  }
}

这个结果在这里很好,但是我在输出中得到了转义字符-

[
    " {\n  \"totalsize\" : 128,\n  \"devicetypeuno\" : \"2\"} ",
    " {\n  \"totalsize\" : 128,\n  \"devicetypeuno\" : \"2\"} "
]
嫩脚

我使用以下方法做到了-

   case HttpRequest(POST, Uri.Path("/decodedata"), _, entity, _) =>
        val chunk = Unmarshal(entity).to[List[DataChunk]]
        val deviceData = Await.result(chunk, 1.second)
        implicit val formats = org.json4s.DefaultFormats
        val resp = deviceData
          .map(data =>
            Serialization.write(ParserManager(Hex.decodeHex(data.rawData.replaceAll("\\s", "").toCharArray)))
          ).mkString

        HttpResponse(entity = HttpEntity(ContentTypes.`application/json`, resp))



  case class DataChunk(rawData: String)

  object DataChunk {
    implicit val dataChunkJsonFormat: RootJsonFormat[DataChunk] = jsonFormat1(DataChunk.apply)
  }

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何在Golang中从HTTP GET请求发送JSON响应?

无法将JSON作为正文发送给GO中的HTTP POST请求

如何发送http请求并检索json响应C ++ Boost

如何使HTTPS(不是HTTP)请求使用akka-http?

akka-http:如何设置响应头

如何在Akka中管理HTTP请求?

如何使用json4s从akka-http响应实体读取json响应

如何重试失败的akka-http请求流的编组?

Akka-Http:如何测试请求

如何在akka-http中读取查询参数?

如何使用akka http发送文件作为响应?

更新:如何使用http包在流星中将Json数据作为POST请求发送

如何从Akka HTTP请求中读取Cookie值

Akka-http:如何将响应映射到对象

如何使用Akka HTTP表示表单数据请求?

如何管理Http到Akka Stream并将消息发送到Kafka?

Akka Alppaka Producer如何与Akka HTTP集成

从基于json数组的akka http响应获取实体的序列

如何使用Akka-Http进行并行Http请求?

如何发送csv文件作为akka http响应?

如何在akka http中向POST请求添加重试?

如何发出HTTP Post请求并以JSON Android获取响应

如何使用Akka-http请求JSON或XML?

Akka-http如何记录服务器错误响应?

Django如何读取http请求并发送http响应

Akka Http - 如何从 HttpResponse 标头读取 Content-Disposition?

Swift 将 http 请求响应作为数组

如何在 JavaScript 函数中使用来自 ajax 请求的 json 响应作为 Javascript 数组

如何使 akka-http 将 GET 请求转发到 POST 请求并更改属性?