java Java中的URL格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7779152/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
URL formatting in Java
提问by Raj Gupta
String arg="http://www.example.com/user.php?id=<URLRequest Method='GetByUID' />";
java.net.URI uri = new java.net.URI( arg );
java.awt.Desktop desktop = java.awt.Desktop.getDesktop();
desktop.browse( uri );
I want to open the given link in default browser with the above code but it says the url is invalid...i tried escaping characters like ' also but its not working. If i replace String arg="www.google.com"; then there is no problem and I am able to open google.com. Please help.
我想用上面的代码在默认浏览器中打开给定的链接,但它说 url 无效......我也尝试转义像 ' 这样的字符,但它不起作用。如果我替换 String arg="www.google.com"; 那么就没有问题了,我可以打开 google.com。请帮忙。
回答by Ryan Stewart
Your string contains characters that aren't valid in a URI, per RFC 2396. You need to properly encode the query parameters. Many utilities support that, like the standard URLEncoder(lower level), JAX-RS UriBuilder, Spring UriUtils, Apache HttpClient URLEncodedUtilsand so on.
根据RFC 2396,您的字符串包含在 URI 中无效的字符。您需要正确编码查询参数。许多实用程序都支持它,例如标准的URLEncoder(较低级别)、JAX-RS UriBuilder、Spring UriUtils、Apache HttpClient URLEncodedUtils等。
Edit:Oh, and the URI class can handle it, too, but you have to use a different constructor:
编辑:哦,URI 类也可以处理它,但是您必须使用不同的构造函数:
URI uri = new URI("http", "foo.com", null, "a=<some garbage>&b= |{http://foo.com?a=%3Csome%20garbage%3E&b=%20%7C%7Bimport java.net.URL;
import java.net.URLEncoder;
class ARealURL {
public static void main(String[] args) throws Exception {
String s1 = "http://www.example.com/user.php?id=";
String param = "<URLRequest Method='GetByUID' />";
String encodedParam = URLEncoder.encode(param,"UTF-8");
URL url = new URL(s1+encodedParam);
System.out.println(url);
}
}
m3%20m0r3%20garbage%7D%7C%20&c=imokay
m3 m0r3 garbage}| &c=imokay", null);
System.out.println(uri);
Outputs:
输出:
http://www.example.com/user.php?id=%3CURLRequest+Method%3D%27GetByUID%27+%2F%3E
which, while ugly, is the correct representation.
虽然丑陋,但这是正确的表示。
回答by lobster1234
Thats because it isinvalid. <URLRequest Method='GetByUID' />
should be replaced by the value of the id
, or an expression that returns the id
which you can concatenate with the arg
string. Something like
那是因为它是无效的。<URLRequest Method='GetByUID' />
应替换为 的值id
,或返回id
可以与arg
字符串连接的表达式。就像是
String arg="http://www.example.com/user.php?id="+getByUID(someUid);
String arg="http://www.example.com/user.php?id="+getByUID(someUid);