簡體   English   中英

用於修復格式錯誤的URI的Scala或Java庫

[英]Scala or Java Library for fixing malformed URIs

有沒有人知道一個好的Scala或Java庫可以解決格式錯誤的URI中的常見問題,例如包含應該被轉義但不是的字符?

我已經測試了一些庫,包括現在遺留的HTTPClient的URIUtil,但我覺得沒有找到任何可行的解決方案。 通常情況下,我在這種類型的java.net.URI構造方面取得了足夠的成功:

/**
 * Tries to construct an url by breaking it up into its smallest elements
 * and encode each component individually using the full URI constructor:
 *
 *    foo://example.com:8042/over/there?name=ferret#nose
 *    \_/   \______________/\_________/ \_________/ \__/
 *     |           |            |            |        |
 *  scheme     authority       path        query   fragment
 */
public URI parseUrl(String s) throws Exception {
   URL u = new URL(s);
   return new URI(
        u.getProtocol(), 
        u.getAuthority(), 
        u.getPath(),
        u.getQuery(), 
        u.getRef());
}

可以與以下程序結合使用。 它重復解碼URL直到解碼的字符串不改變,這對於例如雙重編碼是有用的。 請注意,為了簡單起見,此示例不具有任何故障保護等功能。

public String urlDecode(String url, String encoding) throws UnsupportedEncodingException, IllegalArgumentException {
    String result = URLDecoder.decode(url, encoding);
    return result.equals(url) ? result : urlDecode(result, encoding);
}

我建議不要使用java.net.URLEncoder來編碼URI。 盡管有這個名字,但它對編碼URL並不好,因為它不遵循rfc3986標准,而是編碼為application/x-www-form-urlencoded MIME格式( 在這里閱讀更多

為了在Scala中編碼URI,我建議使用spray-http的Uri類。 scala-uri是另一種選擇(免責聲明:我是作者)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM