【问题标题】:Url encode a part of a string in javaUrl在java中编码字符串的一部分
【发布时间】:2019-03-04 18:39:31
【问题描述】:

我有一个 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)

是否有任何现有的库可以做到这一点?

【问题讨论】:

  • 为什么在构建链接时不对最后一部分进行编码?

标签: java string urlencode


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-23
    • 1970-01-01
    • 2022-07-20
    • 1970-01-01
    相关资源
    最近更新 更多