URL用Java编码字符串的一部分

时间:2019-03-04 18:39:31

标签: java string urlencode

我有一个url,其中有几个我不想被编码的宏,但是其余部分应该是。 例如-

https://example.net/adaf/${ABC}/asd/${WSC}/ 

应编码为

https%3A%2F%2Fexample.net%2Fadaf%2F${ABC}%2Fasd%2F${WSC}%2F

URLEncoder.encode(string, encoding)对整个字符串进行编码。我需要一种函数-encode(string, start, end, encoding)

有没有现成的库?

1 个答案:

答案 0 :(得分:0)

AFAIK没有标准库提供像这样的重载方法。但是您可以围绕标准API构建自定义包装函数。

要实现您的目标,代码应类似于:

public static void main(String[] args) throws UnsupportedEncodingException {
    String source = "https://example.net/adaf/${ABC}/asd/${WSC}/";
    String target = "https%3A%2F%2Fexample.net%2Fadaf%2F${ABC}%2Fasd%2F${WSC}%2F";

    String encodedUrl = encode(source, 0, 25, StandardCharsets.UTF_8.name()) +
            source.substring(25, 31) +
            encode(source, 31, 36, StandardCharsets.UTF_8.name()) +
            source.substring(36, 42) +
            encode(source, 42, 43, StandardCharsets.UTF_8.name());


    System.out.println(encodedUrl);
    System.out.println(encodedUrl.equals(target));
}

static String encode(String s, int start, int end, String encoding) throws UnsupportedEncodingException {
    return URLEncoder.encode(s.substring(start, end), StandardCharsets.UTF_8.name());
}
  

https%3A%2F%2Fexample.net%2Fadaf%2F${ABC}%2Fasd%2F${WSC}%2F

     

true

但是这将非常混乱。

作为替代方案,您可以在编码后简单地将不想转义的字符集替换为其原始值:

public static void main(String[] args) throws UnsupportedEncodingException {
    String source = "https://example.net/adaf/${ABC}/asd/${WSC}/";
    String target = "https%3A%2F%2Fexample.net%2Fadaf%2F${ABC}%2Fasd%2F${WSC}%2F";

    String encodedUrl = URLEncoder.encode(source, StandardCharsets.UTF_8.name())
            .replaceAll("%24", "\\$")
            .replaceAll("%7B", "{")
            .replaceAll("%7D", "}");


    System.out.println(encodedUrl);
    System.out.println(encodedUrl.equals(target));
}
  

https%3A%2F%2Fexample.net%2Fadaf%2F${ABC}%2Fasd%2F${WSC}%2F

     

true