用Java编码带有空格的URL时出现错误。

huangapple go评论74阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2020年8月6日 20:40:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/63283848.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定