Akka-HTTP服务器支持https
2021-03-21 20:23
标签:can system 是什么 server 导致 col https hang manual 3、但是不是什么官方的证书都可以的。有严格要求 4 、一个server服务器能够同时允许https和http,但是两种方法一起运行是因为是不能是同一个地址,会报错。 一个server需要同时运行http和https的话就需要准备两个端口地址 即单个应用程序中运行HTTP和HTTPS服务器,则可以调用 具体代码如下: Akka-HTTP服务器支持https 标签:can system 是什么 server 导致 col https hang manual 原文地址:https://www.cnblogs.com/0205gt/p/12719408.html
import java.io.InputStream
import java.security.{ SecureRandom, KeyStore }
import javax.net.ssl.{ SSLContext, TrustManagerFactory, KeyManagerFactory }
import akka.actor.ActorSystem
import akka.http.scaladsl.server.{ Route, Directives }
import akka.http.scaladsl.{ ConnectionContext, HttpsConnectionContext, Http }
import akka.stream.ActorMaterializer
import com.typesafe.sslconfig.akka.AkkaSSLConfig
implicit val system = ActorSystem()
implicit val mat = ActorMaterializer()
implicit val dispatcher = system.dispatcher
// Manual HTTPS configuration
val password: Array[Char] = "change me".toCharArray // do not store passwords in code, read them from somewhere safe!
val ks: KeyStore = KeyStore.getInstance("PKCS12")
val keystore: InputStream = getClass.getClassLoader.getResourceAsStream("server.p12")
//数字证书是固定的p12文件格式
require(keystore != null, "Keystore required!")
ks.load(keystore, password)
val keyManagerFactory: KeyManagerFactory = KeyManagerFactory.getInstance("SunX509")
keyManagerFactory.init(ks, password)
val tmf: TrustManagerFactory = TrustManagerFactory.getInstance("SunX509")
tmf.init(ks)
val sslContext: SSLContext = SSLContext.getInstance("TLS")
sslContext.init(keyManagerFactory.getKeyManagers, tmf.getTrustManagers, new SecureRandom)
val https: HttpsConnectionContext = ConnectionContext.https(sslContext)
bind...
两次方法,一种用于HTTPS,另一种用于HTTP。上面的2的https的代码也要调用
// you can run both HTTP and HTTPS in the same application as follows:
val commonRoutes: Route = get { complete("Hello world!") }
Http().bindAndHandle(commonRoutes, "127.0.0.1", 443, connectionContext = https)
Http().bindAndHandle(commonRoutes, "127.0.0.1", 80)
文章标题:Akka-HTTP服务器支持https
文章链接:http://soscw.com/index.php/essay/67301.html