我遵循示例here在Scala中创建一个websocket客户端。我想在websocket请求中传递自定义标头。我通过扩展CustomHeader
创建了HttpHeader
课程。
final class CustomHeader(headerName: String, headerValue: String) extends HttpHeader {
override def name(): String = headerName
override def value(): String = headerValue
override def lowercaseName(): String = name.toLowerCase
override def renderInRequests(): Boolean = true
override def renderInResponses(): Boolean = true
}
然后在客户端,
val headers = Seq(new CustomHeader("X-Auth-Token", authToken))
val request = new WebSocketRequest(uri = "ws://localhost:9035", extraHeaders = headers)
当我运行activator compile
时,它会抛出以下错误:
type mismatch;
[error] found : Seq[com.apple.geo.neutron.services.notification.event.CustomHeader]
[error] required: scala.collection.immutable.Seq[akka.http.scaladsl.model.HttpHeader]
[error] Error occurred in an application involving default arguments.
[error] val request = new WebSocketRequest(uri = "ws://localhost:9035", extraHeaders = headers)
如何解决此错误,或者向websocket请求添加自定义标头?
答案 0 :(得分:0)
Seq
这里不是一个不可变的Seq
。尝试将headers
定义为:
val headers = scala.collection.immutable.Seq(new CustomHeader("X-Auth-Token", authToken))
答案 1 :(得分:0)
回答我自己的问题。感谢this线程,我发现了一种添加自定义标头的工作方式。这是我做的:
final class CustomHeader(headerValue: String) extends ModeledCustomHeader[CustomHeader] {
override val companion = CustomHeader
override def value(): String = headerValue
override def renderInRequests(): Boolean = true
override def renderInResponses(): Boolean = true
}
object CustomHeader extends ModeledCustomHeaderCompanion[CustomHeader] {
override val name = "X-Auth-Token"
override def parse(value: String) = Try(new CustomHeader(value))
}
然后,websocket请求创建为:
val headers = scala.collection.immutable.Seq(new CustomHeader(authToken))
val request = new WebSocketRequest(uri = "ws://localhost:9035", extraHeaders = headers)