3

httpまたは... とは異なるプロトコルを含む可能性のある URL を解析する必要があり、コンストラクターがクラッシュするような URL でオブジェクトhttpsを作成しようとすると、次のようなものを実装しました。java.net.URLnio://localhost:61616

def parseURL(spec: String): (String, String, Int, String) = {
  import java.net.URL

  var protocol: String = null

  val url = spec.split("://") match {
    case parts if parts.length > 1 =>
      protocol = parts(0)
      new URL(if (protocol == "http" || protocol == "https" ) spec else "http://" + parts(1))
    case _ => new URL("http" + spec.dropWhile(_ == '/'))
  } 

  var port = url.getPort; if (port < 0) port = url.getDefaultPort
  (protocol, url.getHost, port, url.getFile)
}

特定の URL にhttpまたは以外のプロトコルが含まれている場合はhttps、それを変数に保存してから、強制的にクラッシュせずに解析さhttpせます。java.net.URL

この問題を解決するよりエレガントな方法はありますか?

4

1 に答える 1

10

非標準プロトコルには java.net.URI を使用できます。

new java.net.URI("nio://localhost:61616").getScheme() // returns nio

API に似た Scala が必要な場合は、https://github.com/lemonlabsuk/scala-uriを確認してください。

于 2015-09-25T06:42:46.650 に答える