gpt4 book ai didi

java - java中的url编码字符串的一部分

转载 作者:太空宇宙 更新时间:2023-11-04 09:49:17 25 4
gpt4 key购买 nike

我有一个网址,其中有一些我不想编码的宏,但其余部分应该编码。例如 -

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)

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

最佳答案

据我所知,没有标准库提供这样的重载方法。但是您可以围绕标准 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

关于java - java中的url编码字符串的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54989528/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com