2012-12-21 69 views
2

我有以下網址:階:更改URL的端口

ws://chat-jugar.rhcloud.com/room/chat?username=felipe 

而且我想只需添加一個非默認端口,這樣

ws://chat-jugar.rhcloud.com:8000/room/chat?username=felipe 

我第一次嘗試用的java.net.URL開始解析和處理的URL,但我得到了

scala> val u = new java.net.URL("ws://chat-jugar.rhcloud.com/room/chat?username=felipe") 
java.net.MalformedURLException: unknown protocol: ws 
at java.net.URL.<init>(URL.java:592) 
at java.net.URL.<init>(URL.java:482) 
at java.net.URL.<init>(URL.java:431) 

我不想惹正則表達式,以避免錯過一些奇怪的情況下(但沒關係,如果沒有其他選擇,當然...)

這是什麼最好的方法?

回答

4

您可以使用java.net.URI解壓縮到uri的某些部分,然後構建添加了端口的新uri字符串。例如:

val uri = URI.create("ws://chat-jugar.rhcloud.com/room/chat?username=felipe") 

val newUriString = "%s://%s:%d%s?%s".format(uri.getScheme, uri.getHost, 8000, uri.getPath, uri.getQuery) 

newUriString: String = ws://chat-jugar.rhcloud.com:8000/room/chat?username=felipe 
1

您可以使用java.net.URI代替。

def changePort(uri: java.net.URI, port: Int) = new java.net.URI(uri.getScheme, uri.getUserInfo, uri.getHost, port, uri.getPath, uri.getQuery, uri.getFragment) 

然後

scala> changePort(new java.net.URI("ws://chat-jugar.rhcloud.com/room/chat?username=felipe"), 8000).toString 
res: java.lang.String = ws://chat-jugar.rhcloud.com:80/room/chat?username=felipe 
0

你可能想嘗試一下我的Bee Client API,其中包含了PartialURL類處理,根據其結構的網址(完整的或其他)。

一般的想法是從一個字符串或URL構造一個,然後改變你需要的任何部分,例如,

import uk.co.bigbeeconsultants.http.url._ 
val url = PartialURL("ws://chat-jugar.rhcloud.com/room/chat?username=felipe") 
val url8080 = url.copy(endpoint = Some(url.endpoint.get.copy(port = Some(8080)))) 
4

只是爲了記錄在案,這是我使用的java.net.URI中來如drexin告訴

package utils.http 

case class Uri(
    protocol: String, userInfo: String, 
    host: String, port: Int, 
    path: String, query: String, fragment: String 
) { 
    lazy val javaURI = { 
    new java.net.URI(
     protocol, userInfo, 
     host, port, 
     path, query, fragment 
    ) 
    } 

    override def toString = { 
    javaURI.toString 
    } 
} 

object Uri { 
    def apply(uri: String): Uri = { 
    val parsedUri = new java.net.URI(uri) 
    Uri(
     parsedUri.getScheme, parsedUri.getUserInfo, 
     parsedUri.getHost, parsedUri.getPort, 
     parsedUri.getPath, parsedUri.getQuery, parsedUri.getFragment 
    ) 
    } 
} 

的小工具幫助和我這樣使用它(從遊戲控制檯):

scala> import utils.http.Uri 
import utils.http.Uri 

scala> Uri("ws://chat-jugar.rhcloud.com/room/chat?username=felipe").copy(port=8000).toString 
res0: java.lang.String = ws://chat-jugar.rhcloud.com:8000/room/chat?username=felipe 
+2

我真的很喜歡你如何利用case類的參數默認機制來創建一個只改變了一個參數的新URI。同樣的機制適用於1..n個參數的任何變化。 – chaotic3quilibrium

+0

yeap,複製方法確實是一件好事... – opensas

1

位遲到了,但你可以scala-uri(免責聲明做到這一點:這是我自己的圖書館):

import com.github.theon.uri.Uri._ 

val uri = "ws://chat-jugar.rhcloud.com/room/chat?username=felipe" 
val newUri = uri.copy(port = Some(8000)) 

newUri.toString //This is: ws://chat-jugar.rhcloud.com:8000/room/chat?username=felipe 

它在Maven中心有售。詳細信息在這裏:https://github.com/theon/scala-uri