简体   繁体   English

我如何在Java中转义URL(文档不清楚)?

[英]How I can escape URL in Java (docs are not clear)?

I have found various posts where escaping in Java is done with java.net.URLEncoder.encode . 我找到了各种帖子,用java.net.URLEncoder.encode完成Java中的转义。 However I have found in docs for URL that: 但是我在URL docs中找到了:

The URLEncoder and URLDecoder classes can also be used, but only for HTML form encoding, which is not the same as the encoding scheme defined in RFC2396. 也可以使用URLEncoderURLDecoder类,但仅用于HTML表单编码,这与RFC2396中定义的编码方案不同。

Can someone explain me this situation? 有人能解释一下这种情况吗?

You can use URI. 您可以使用URI。 For example: 例如:

URI uri = new URI("http","google.com","/ a z.html","asd= z%#@@#");
System.out.println(uri.toString());
//returns http://google.com/%20a%20z.html#asd=%20z%25%23@@%23

note that the single parameter constructor does not escape characters, so it'll throw an exception if you do something like: 请注意,单个参数构造函数不会转义字符,因此如果您执行以下操作,它将引发异常:

URI uri = new URI("http://google.com/ a z.html?asd= z%#@@#");

From a URI you can get a URL by doing: 从URI中,您可以通过执行以下操作获取URL:

URL uri.toURL();

The document correctly advises to use the URI class. 该文档正确建议使用URI类。 The reason URLEncoder is still mentioned is I guess historical cause URLEncoder has been there since 1.0 while URI was added in 1.4. 仍然提到URLEncoder的原因是我猜历史原因URLEncoder自1.0以来一直存在,而在1.4中添加了URI。

URLEncoder, despite its name, is for encoding URL arguments or POST parameters. URLEncoder,尽管它的名字,用于编码URL 参数或POST参数。

The correct way to encode URLs proper, before the query string, is via new URI(null, String, null).toURL(). 在查询字符串之前正确编码URL的正确方法是通过新URI(null,String,null).toURL()。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM