简体   繁体   English

如何使用Java编码URL

[英]How to encode an URL with Java

Given an URL such as this one, 给定这样的网址,

http://www.example.com/some directory/some file http://www.example.com/some目录/ some文件

how do you encode this URL? 您如何编码此URL? Browsers automatically encode it. 浏览器会自动对其进行编码。 In Java I couldn't find a ready made function. 在Java中,我找不到现成的函数。 I suspect there should be such a function because this is generally needed. 我怀疑应该有这样的功能,因为通常需要这样做。

When I try to use the URI class using the constructor with single String, and parse components of the URL, such as authority, path, etc, it gives error because it expects an encoded URL. 当我尝试使用带有单个String的构造函数的URI类,并解析URL的组件(例如权限,路径等)时,由于期望使用编码的URL,因此会出现错误。

Do you know a ready made function that will produce, for example in this case: 您是否知道会产生一个现成的函数,例如在这种情况下:

http://www.example.com/some%20directory/some%20file http://www.example.com/some%20directory/some%20file

Try this: 尝试这个:

final URL url = new URL("http://www.example.com/some directory/some file");
final URI uri = new URI(url.getProtocol(), url.getHost(), url.getPath(), null);

System.out.println(uri.toASCIIString());

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

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