标签: akka-http

Akka-http Java API示例代码/文档

任何人都可以使用JAVA API向我指出akka-http的工作示例.

提前致谢.

java httpclient akka akka-http

6
推荐指数
1
解决办法
3312
查看次数

传出连接流已关闭

我有一个行为的演员:

def receive: Receive = {
    case Info(message) =>
      val res = send("INFO:"  + message)
      installAckHook(res)
    case Warning(message) =>
      val res = send("WARNING:"  + message)
      installAckHook(res)
    case Error(message) =>
      val res = send("ERROR:" + message)
      installAckHook(res)
  }

 private def installAckHook[T](fut: Future[T]): Unit = {
    val answerTo = sender()

    fut.onComplete {
      case Success(_) => answerTo ! "OK"
      case Failure(ex) => answerTo ! ex
    }
  }


  private def send(message: String): Future[HttpResponse] = {
    import context.system
    val payload: Payload = Payload(text = message, …
Run Code Online (Sandbox Code Playgroud)

akka-http

6
推荐指数
1
解决办法
1590
查看次数

如何使用akka-http进行HTTPS(非HTTP)请求?

我使用以下代码与akka-httpAkka Actor内的库发出HTTP请求:

implicit val materializer = ActorFlowMaterializer()
implicit val system = context.system

val request = HttpRequest(HttpMethods.GET, "http://ya.ru")
val content = for {
  response <- Http().singleRequest(request)
  content <- Unmarshal(response.entity).to[String]
} yield content
Run Code Online (Sandbox Code Playgroud)

一切工作正常,但现在我想使HTTPS请求(只需更换http://https://).之后,content变量将包含以下响应:

<head><title>400 The plain HTTP request was sent to HTTPS port</title></head>
<body bgcolor="white">
<center><h1>400 Bad Request</h1></center>
<center>The plain HTTP request was sent to HTTPS port</center>
<hr><center>nginx</center>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

似乎akka-http不支持HTTPS协议.发送HTTPS请求是否正确或可能akka-http

akka akka-http

6
推荐指数
1
解决办法
2103
查看次数

如何在Akka-http 2.4.1中包含application/x-www-form-urlencoded HttpHeader?

我正在使用Akka Http 2.4.1向twitter api发布https请求.

根据他们的文档,我需要两个httpheaders.即,授权和ContentType.

引用他们的文档:

请求必须包含一个Content-Type标头,其值为application/x-www-form-urlencoded; charset = UTF-8.

这是我的代码:

val authorization = Authorization(BasicHttpCredentials(key, secret))

/*
   This header is removed from the request with the following explanation!
   "Explicitly set HTTP header 'Content-Type: application/x-www-form-urlencoded;' is ignored, illegal RawHeader"
*/
val contentType = RawHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8")

Http().singleRequest(
    HttpRequest(
        uri = Uri("https://api.twitter.com/oauth2/token"),
        method = HttpMethods.POST,
        headers = List(authorization, contentType),
        entity = HttpEntity(`text/plain(UTF-8)`, "grant_type=client_credentials"),
        protocol = HttpProtocols.`HTTP/1.1`))
Run Code Online (Sandbox Code Playgroud)

如何使用Akka-http 2.4.1 包含Content-Type带有值的标头application/x-www-form-urlencoded;charset=UTF-8

scala akka-http

6
推荐指数
1
解决办法
3529
查看次数

如何在Web插槽连接中从订阅者向发布者发送反应流中的消息

我的应用程序有一个Akka-Websocket接口.Web套接字由actor-subscriber和actor发布者组成.订户通过将命令发送到相应的actor来处理命令.发布者侦听事件流并将更新信息发布回流(最后发送到客户端).这很好用.

我的问题:订阅者如何将事件发送回流?例如,确认执行收到的命令.

public class WebSocketApp extends HttpApp {

  private static final Gson gson = new Gson();

  @Override
  public Route createRoute() {
    return get(
        path("metrics").route(handleWebSocketMessages(metrics()))
        );
  }

  private Flow<Message, Message, ?> metrics() {
    Sink<Message, ActorRef> metricsSink = Sink.actorSubscriber(WebSocketCommandSubscriber.props());
    Source<Message, ActorRef> metricsSource = 
        Source.actorPublisher(WebSocketDataPublisherActor.props())
        .map((measurementData) -> TextMessage.create(gson.toJson(measurementData)));
    return Flow.fromSinkAndSource(metricsSink, metricsSource);
  }
}
Run Code Online (Sandbox Code Playgroud)

一个很好的解决方案可能是,订阅actor(WebSocketCommandSubscriber上面代码中的actor)可以将消息发送回流,如sender().tell(...)...

akka akka-stream akka-http

6
推荐指数
1
解决办法
904
查看次数

akka http配置中的空闲超时和请求超时有什么区别?

我去了文档,发现了这些#空闲连接将自动关闭的时间。# 设置为infinite完全禁用空闲连接超时。空闲超时 = 10 秒

# Defines the default time period within which the application has to
# produce an HttpResponse for any given HttpRequest it received.
# The timeout begins to run when the *end* of the request has been
# received, so even potentially long uploads can have a short timeout.
# Set to `infinite` to completely disable request timeout checking.
#
# If this setting is not `infinite` the HTTP server layer attaches a
# …
Run Code Online (Sandbox Code Playgroud)

scala connection-timeout akka-http

6
推荐指数
1
解决办法
7334
查看次数

Akka Http.get(ActorSystem)导致intellij中的Ambiguous方法调用

intellij在子类指定更具体的返回类型时遇到问题.这是Akka的Http.get(ActorSystem)方法的情况.这是向JB报告的问题,但他们还没有回复.

SCL-12302

java scala intellij-idea akka akka-http

6
推荐指数
1
解决办法
953
查看次数

Akka HTTP:找不到请求的资源

我在Akka HTTP 中的第一步使用Akka HTTP“最小示例”

private Route createRoute() {
  return route(
    path("hello", () ->
      get(() ->
        complete("<h1>Say hello to akka-http</h1>"))));
}
Run Code Online (Sandbox Code Playgroud)

现在我想向 my 中添加一个路由resources/web/test.html,类似于“指令”页面上的示例:

private Route createRoute() {
  return route(
    pathSingleSlash(() ->
      getFromResource("web/test.html")
    ),
    path("hello", () ->
      complete("<h1>Say hello to akka-http</h1>")));
}
Run Code Online (Sandbox Code Playgroud)

http://localhost:8080向我展示了以下内容:

The requested resource could not be found.
Run Code Online (Sandbox Code Playgroud)

java akka-http

6
推荐指数
0
解决办法
1143
查看次数

akka http使用Json支持和xmlsupport

我想在部门为"hr"时以xml格式打印数据,但在部门为"tech"时以json格式打印数据.

我们可以使用spray-json支持https://doc.akka.io/docs/akka-http/current/common/json-support.html和XML支持 https://doc.akka.io/docs/akka-http /current/common/xml-support.html在一起

 private[rest] def route =
  (pathPrefix("employee") & get) {
    path(Segment) { id =>
      parameters('department ? "") { (flag) =>
        extractUri { uri =>
          complete {
            flag match {
              case "hr": =>  {

            HttpEntity(MediaTypes.`application/xml`.withCharset(HttpCharsets.`UTF-8`),"hr department")
            }
              case "tech" =>{
                HttpEntity(ContentType(MediaTypes.`application/json`), mapper.writeValueAsString("tech department"))

              }

            }
          }
        }
      }
    }
  }
Run Code Online (Sandbox Code Playgroud)

解决方案我试过我通过使用JsonProtocols和ScalaXmlSupport来尝试下面我得到编译错误预期ToResponseMarshallable但找到了Department

case class department(name:String)
private[rest] def route =
  (pathPrefix("employee") & get) {
    path(Segment) { id =>
      parameters('department ? "") { (flag) =>
        extractUri { uri => …
Run Code Online (Sandbox Code Playgroud)

scala akka-http

6
推荐指数
1
解决办法
358
查看次数

如何将我的路由包装在身份验证指令中,然后为我的路由提供自定义类的可见性以供访问

我的 API 客户端将在标头或查询字符串中传递会话令牌,如下所示:

Http Header with key/value like MyApp-Token abc123
Url:
  https://api.example.com/v1/board?authToken=abc123

 val secureRoutes =
        authenticateToken() { authenticatedContext =>
           path("board") {
             get {
               complete(s"board#index route ${authenticatedContext.user.username}")
             }
           }
       }
Run Code Online (Sandbox Code Playgroud)

是否有一个内置指令可以为我执行此操作,或者我是否必须以某种方式创建自己的自定义指令,该指令将首先查看 HTTP 标头,如果不存在,则查看是否有查询字符串值钥匙authToken

如果我必须创建自定义指令,我可以遵循或学习哪些示例?

我知道我可以使用内置指令获取 HTTP 标头:

          headerValueByName("x-authToken") { authToken =>
            get {
              complete(s"board#index route 2.1 $authToken")
            }
          }
Run Code Online (Sandbox Code Playgroud)

还有一个从查询字符串中获取值的指令:

  parameter("authToken") { authToken => 

  ...
  }
Run Code Online (Sandbox Code Playgroud)

我如何将它们结合起来,然后在内部我想要进行数据库调用,然后我不想返回,而是authToken想返回一个自定义案例类,该类将包含我刚刚从数据库加载的数据,例如:

case class AuthenticatedContext(authToken: String, user: User, ...)
Run Code Online (Sandbox Code Playgroud)

authentication akka-http

6
推荐指数
1
解决办法
213
查看次数