Url在java中编码字符串的一部分

问题描述 投票:1回答:1

我有一个网址,其中我有很少的宏,我不想编码,但剩下的部分应该是。例如 -

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)

有没有现有的图书馆这样做?

java string urlencode
1个回答
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

© www.soinside.com 2019 - 2024. All rights reserved.