从url字符串中删除get参数的最佳方法是什么?
问题描述:
我有以下网址字符串:
http://www.xyz/path1/path2/path3?param1=value1¶m2=value2 。
我需要获取没有参数的url,因此结果应为:
I need to get this url without parameters, so the result should be:
http://www.xyz/path1/path2/path3 。
我这样做了:
private String getUrlWithoutParameters(String url)
{
return url.substring(0,url.lastIndexOf('?'));
}
还有更好的办法吗?
答
可能不是最有效的方式,但更安全类型:
Probably not the most efficient way, but more type safe :
private String getUrlWithoutParameters(String url) throws URISyntaxException {
URI uri = new URI(url);
return new URI(uri.getScheme(),
uri.getAuthority(),
uri.getPath(),
null, // Ignore the query part of the input url
uri.getFragment()).toString();
}