- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我是 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\"} "
]
最佳答案
这是一个示例程序,它读取一个 json 值数组并返回一个新的 json。
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.server.Directives._
import akka.stream.ActorMaterializer
import akka.util.Timeout
import de.heikoseeberger.akkahttpcirce.FailFastCirceSupport
import io.circe.generic.semiauto
import io.circe.{Decoder, Encoder}
import scala.concurrent.duration._
import scala.io.StdIn
object WebServer3 extends FailFastCirceSupport {
def main(args: Array[String]) {
implicit val system = ActorSystem("my-system")
implicit val materializer = ActorMaterializer()
implicit val executionContext = system.dispatcher
implicit val timeout: Timeout = 2.seconds
case class Zoo(foo: String, bar: String)
case class DoneZoo(message: String)
implicit val zooDecoder: Decoder[Zoo] = semiauto.deriveDecoder[Zoo]
implicit val zooEncoder: Encoder[Zoo] = semiauto.deriveEncoder[Zoo]
implicit val doneDecoder: Decoder[DoneZoo] = semiauto.deriveDecoder[DoneZoo]
implicit val doneEnecoder: Encoder[DoneZoo] =
semiauto.deriveEncoder[DoneZoo]
val route = path("parseData") {
entity(as[List[Zoo]]) { zoo =>
zoo.foreach(println)
complete(DoneZoo(zoo.foldLeft("") {
case (agg, el) => agg + el.bar + el.foo + ";"
}))
}
}
val bindingFuture = Http().bindAndHandle(route, "localhost", 8080)
println(s"Server online at http://localhost:8080/\nPress RETURN to stop...")
StdIn.readLine()
val _ = bindingFuture.flatMap(_.unbind())
}
}
json 是在案例类和circe semi auto derivation 的帮助下定义的.这将创建用于 json 转换的编码器/解码器类。您必须将这些类型转换为用于实体编码的 Akka 特定类型,这是在 de.heikoseeberger.akkahttpcirce.FailFastCirceSupport 的帮助下隐式完成的。
在此之后,您可以使用 akka route dsl定义您的 http 路由。 entity(as[List[Zoo]])
将 http 主体读取为 json 并返回 List[Zoo]
您可以借助 curl
curl -v -X POST -H 'Content-type: application/json' --data '[{"foo": "Foo", "bar": "Bar"}]' http://localhost:8080/parseData
Note: Unnecessary use of -X or --request, POST is already inferred.
* Trying ::1...
* TCP_NODELAY set
* Connection failed
* connect to ::1 port 8080 failed: Connection refused
* Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 8080 (#0)
> POST /parseData HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.64.1
> Accept: */*
> Content-type: application/json
> Content-Length: 30
>
* upload completely sent off: 30 out of 30 bytes
< HTTP/1.1 200 OK
< Server: akka-http/10.1.7
< Date: Tue, 15 Oct 2019 08:46:56 GMT
< Content-Type: application/json
< Content-Length: 18
<
* Connection #0 to host localhost left intact
{"message":"DONE"}* Closing connection 0
编辑:
Json 序列化必须留给 akka 在指令 entity(as[])
中处理请求和 complete
响应。不要手动创建 JSON。
关于scala - 如何从 Akka HTTP POST 请求中读取 JSON 正文并将最终响应作为 JSON 数组发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58390371/
考虑需要与 iOS 5 和 iOS 6 兼容的应用。 有没有办法标记纯粹为了 iOS 5 兼容性而存在的代码,以便当部署目标最终更改为 iOS 6 时它显示为编译错误(或警告)? 像这样: #IF_D
我想我知道答案但是...有什么方法可以防止全局变量被稍后执行的 修改吗? ?我知道全局变量首先是不好的,但在必要时,有没有办法让它成为“最终”或“不可变”?欢迎黑客/创造性的解决方案。谢谢 最佳答案
class Foo { final val pi = 3 } 是否每Foo对象有一个 pi成员?因此我应该把 pi在伴生对象中? 最佳答案 如果您担心内存占用,您可以考虑将此字段移动到伴随对象中。
随着可用的 Web 开发框架种类繁多,似乎总是有一种“尝试新事物”的永久动机。因此,我们中的一些人发现自己用一个框架换另一个框架,从来没有对最终结果完全满意。当然,总会有一个特定的 Web 框架可以完
在MDN中指出, If the finally block returns a value, this value becomes the return value of the entire try
我正在尝试用 JavaScript 制作一个基本的井字棋类型游戏。尽管 x 和 y 值在 if 语句的范围内,但除最后一个之外的所有空格都有效。 我不知道为什么最后的 else if 语句不起作用。
我想知道如何使用PowerMock模拟kotlin最终类(class),以便进行测试。我按照指南测试了Java最终类,但仍然出现此错误 Cannot subclass final class 有什么办
考虑以下设置: // debugger class public class Debug { // setting public final static boolean DEBUG
给定以下类(class): public class SomeClass { private final int a; public SomeClass(int a) {
This question already has answers here: What does “final” do if you place it before a variable?
我有一个类PasswordEncryptor,它使用org.jasypt.util.password.StrongPasswordEncryptor作为其字段之一,因为我试图使应用程序“可集群”所有类
我今天有一个关于 StreamReader 类的问题。具体使用文件名参数初始化此类例如: TextReader tr = new StreamReader(fileName); 显然,当此操作完成后,
我想弄清楚什么是使用带锁的 try/finally 的最佳方式。 当我在同一个地方有 lock() 和 unlock() 时,我只使用 try/finally block 作为 JavaDoc还建议:
在 Java 中序列化后是否可以将 final transient 字段设置为任何非默认值?我的用例是一个缓存变量——这就是它是 transient 的原因。我还有一个习惯,就是制作不会改变的 Map
在this问题说 final transient 字段在序列化后不能设置为任何非默认值。那么,为什么我为 aVar1 变量设置了 3,为 aVar3 变量设置了 s3? import java.io.
在Xbox上进行开发时,我使用的是F#规范中最终工作流程的修改版。 Xbox上的.net框架似乎不支持尾部调用。因此,我必须在编译时禁用尾部调用优化。 尽管起初看来这种限制会阻止在计算表达式中使用任何
已结束。此问题正在寻求书籍、工具、软件库等的推荐。它不满足Stack Overflow guidelines 。目前不接受答案。 我们不允许提出寻求书籍、工具、软件库等推荐的问题。您可以编辑问题,以便
我想让我的带有自定义对象的ArrayList成为最终对象,以便对象在设置后无法更改。 我试图这样声明它: private final ArrayList XML = new ArrayList();
我有一个场景,我需要类似于 .NET 的 try-catch-finally block 的内容。 在我的尝试中,我将创建一个#temp表,向其中插入数据并基于#temp处理其他数据集。 先是CATC
对此可能有一个简单的答案,但尝试充分使用 Butterknife,将一些 findViewById 转换为 @BindViews,并注意到我无法在需要声明为 Final 的 View 上使用 Bind
我是一名优秀的程序员,十分优秀!