英文:
Encoding URL with Spaces in Java works incorrectly
问题
我正在尝试进行简单的URL编码,需要对以下URL进行编码:
https://example.org/v1/x/y/Quick Brown Fox/jumps/over/
我使用以下代码:
String url = https://example.org/v1/x/y/Quick Brown Fox/jumps/over/;
url = UrlEncoder.encode(url,"UTF-8");
理想情况下,这应该提供如下输出:
https://example.org/v1/x/y/Quick%20Brown%20Fox/jumps/over/
这是正确的编码。但实际上,它会将空格替换为 +
。
我正在使用JDK 11 - 我需要 %20,因为我正在使用Apache HTTP客户端发送HTTP请求,而URI不会在URL中接受 +
,其中包含空格。
英文:
I am trying a simple url encoding that needs to be done for the URL below:
https://example.org/v1/x/y/Quick Brown Fox/jumps/over/
I use the below code:
String url = https://example.org/v1/x/y/Quick Brown Fox/jumps/over/;
url = UrlEncoder.encode(url,"UTF-8");
Ideally, this should provide output like -
https://example.org/v1/x/y/Quick%20Brown%20Fox/jumps/over/
which is the correct encoding. Instead it ends up replacing space with +
Using JDK 11 - I need %20 because I am using Apache HTTP client to send HTTP request and URI does not take +
in the URL where spaces are present.
答案1
得分: 2
你可以使用URI
类:
URI uri = new URI("https", "//example.org/v1/x/y/Quick Brown Fox/jumps/over/", null);
System.out.println(uri.toASCIIString()); // 应该进行转义
只需注意你需要处理`URISyntaxException`。
英文:
You can use the URI
class:
URI uri = new URI("https", "//example.org/v1/x/y/Quick Brown Fox/jumps/over/", null);
System.out.println(uri.toASCIIString()); // Should be escaped
Just be aware that you need to handle an URISyntaxException
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论