我想将键值对作为查询参数附加到现有 URL。虽然我可以通过检查 URL 是否存在查询部分或片段部分并通过跳过一堆 if 子句来执行附加来做到这一点,但我想知道如果通过 Apache 执行此操作是否有干净的方法公共(public)库或类似的东西。
http://example.com
将是 http://example.com?name=John
http://example.com#fragment
将是 http://example.com?name=John#fragment
http://example.com?email=john.doe@email.com
将是 http://example.com?email=john.doe@email.com&name=约翰
http://example.com?email=john.doe@email.com#fragment
将是 http://example.com?email=john.doe@email。 com&name=John#fragment
我之前已经多次运行过这个场景,我希望在不以任何方式破坏 URL 的情况下执行此操作。
最佳答案
有很多库可以帮助您构建 URI(不要重新发明轮子)。以下三个可以帮助您入门:
Java EE 7
import javax.ws.rs.core.UriBuilder;
...
return UriBuilder.fromUri(url).queryParam(key, value).build();
org.apache.httpcomponents:httpclient:4.5.2
import org.apache.http.client.utils.URIBuilder;
...
return new URIBuilder(url).addParameter(key, value).build();
org.springframework:spring-web:4.2.5.RELEASE
import org.springframework.web.util.UriComponentsBuilder;
...
return UriComponentsBuilder.fromUriString(url).queryParam(key, value).build().toUri();
关于java - 如何将查询参数附加到现有 URL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26177749/