使用Akka-http处理HTTPS请求[java]

时间:2016-04-17 09:10:05

标签: https akka akka-stream akka-http

我正在创建一个小代理来拦截所有本地http请求,然后使用远程代理授权它们。以下是代码段:

Source<IncomingConnection, CompletionStage<ServerBinding>> serverSource =
                Http.get(system).bind(ConnectWithHttps.toHost("localhost", LOCAL_PORT), materializer);
        Authorization authorization = Authorization.basic(USERNAME, PASSWORD);

        Flow<HttpRequest, HttpRequest, NotUsed> applySecurity =
                Flow.of(HttpRequest.class)
                    .map(request -> request.addHeader(authorization));

        Flow<HttpRequest, HttpResponse, CompletionStage<OutgoingConnection>> forwardToProxy =
                Http.get(system).outgoingConnection(ConnectWithHttps.toHost(PROXY_ADDRESS, PROXY_PORT));

        Flow<HttpRequest, HttpResponse, NotUsed> handler =
                Flow.of(HttpRequest.class)
                   .via(applySecurity)
                .via(forwardToProxy);


    serverSource.to(Sink.foreach(conn -> {
             System.out.println("Accepted new connection from " + conn.remoteAddress());
             conn.handleWith(handler, materializer);
                }
 )).run(materializer);

我还需要处理Https请求。但我总是得到这个错误:

[WARN] [04/14/2016 00:07:28.480] [MyActorSystem-akka.actor.default-dispatcher-13] [akka.actor.ActorSystemImpl(MyActorSystem)] Illegal request, responding with status '400 Bad Request': Request is missing required `Host` header: 'Host' header value of request to `eg.linkedin.com:443` doesn't match request target authority: Host header: Some(Host: eg.linkedin.com:443)

我尝试使用“ConnectWithHttps”代替“ConnectHttp”,但事实并非如此。我找不到任何与Https相关的例子

任何想法,谢谢?

注意:

  

文档在Java中没有特别的例子

此致

巴萨姆

1 个答案:

答案 0 :(得分:1)

尝试更改

ConnectWithHttps.toHost("localhost", LOCAL_PORT)

ConnectWithHttps.toHost("localhost", LOCAL_PORT).withCustomHttpsContext(ctx)

然后你需要为此工作创建HttpsConnectionContext(ctx)。如何做到的简单示例:

char[] password = config.getString("https.password").toCharArray();
SSLContext context = SSLContext.getInstance("TLS");
KeyStore ks = KeyStore.getInstance("PKCS12");

ks.load(App.class.getClassLoader().getResourceAsStream("keys/server.p12"), password);
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");

keyManagerFactory.init(ks, password);
context.init(keyManagerFactory.getKeyManagers(), null, new SecureRandom());

HttpsConnectionContext ctx = ConnectionContext.https(context);