我有URL字符串,如:
" http://www.xyz/path1/path2/path3?param1=value1m2=value2 ".
我需要获取没有参数的url,结果应该是:
" http://www.xyz/path1/path2/path3 ".
我这样做了:
private String getUrlWithoutParameters(String url)
{
return url.substring(0,url.lastIndexOf('?'));
}
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法呢?
Era*_*ran 46
可能不是最有效的方式,但更安全类型:
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();
}
Run Code Online (Sandbox Code Playgroud)
使用JAX-RS 2.0 中的javax.ws.rs.core.UriBuilder:
UriBuilder.fromUri("https://www.google.co.nz/search?q=test").replaceQuery(null).build();
Run Code Online (Sandbox Code Playgroud)
使用Spring 中非常相似的org.springframework.web.util.UriBuilder:
UriComponentsBuilder.fromUriString("https://www.google.co.nz/search?q=test").replaceQuery(null).build(Collections.emptyMap());
Run Code Online (Sandbox Code Playgroud)