我该如何在Java中构建URL或URI?是否有惯用的方式或易于实现此操作的库?
我需要能够从请求字符串开始解析/更改各种URL部分(方案、主机、路径、查询字符串)并支持添加和自动编码查询参数。
自从Apache HTTP Component HttpClient 4.1.3版本,官方教程中提到:
public class HttpClientTest {
public static void main(String[] args) throws URISyntaxException {
List<NameValuePair> qparams = new ArrayList<NameValuePair>();
qparams.add(new BasicNameValuePair("q", "httpclient"));
qparams.add(new BasicNameValuePair("btnG", "Google Search"));
qparams.add(new BasicNameValuePair("aq", "f"));
qparams.add(new BasicNameValuePair("oq", null));
URI uri = URIUtils.createURI("http", "www.google.com", -1, "/search",
URLEncodedUtils.format(qparams, "UTF-8"), null);
HttpGet httpget = new HttpGet(uri);
System.out.println(httpget.getURI());
//http://www.google.com/search?q=httpclient&btnG=Google+Search&aq=f&oq=
}
}
编辑:自版本4.2起,URIUtils.createURI()
已被弃用,推荐使用URIBuilder
:
URI uri = new URIBuilder()
.setScheme("http")
.setHost("www.google.com")
.setPath("/search")
.setParameter("q", "httpclient")
.setParameter("btnG", "Google Search")
.setParameter("aq", "f")
.setParameter("oq", "")
.build();
HttpGet httpget = new HttpGet(uri);
System.out.println(httpget.getURI());
作为作者,我可能不是评判我的URL/URI构建器是否“好”的最佳人选,但这便是它:https://github.com/mikaelhg/urlbuilder
我想要的是最简单的完整解决方案,除了JDK外没有任何依赖,所以我不得不自己动手。
使用 HTTPClient 运行良好。
protected static String createUrl(List<NameValuePair> pairs) throws URIException{
HttpMethod method = new GetMethod("http://example.org");
method.setQueryString(pairs.toArray(new NameValuePair[]{}));
return method.getURI().getEscapedURI();
}
有很多库可以帮助你构建URI(不要重复造轮子)。以下是三个库,可供您开始使用:
import javax.ws.rs.core.UriBuilder;
...
return UriBuilder.fromUri(url).queryParam(key, value).build();
import org.apache.http.client.utils.URIBuilder;
...
return new URIBuilder(url).addParameter(key, value).build();
import org.springframework.web.util.UriComponentsBuilder;
...
return UriComponentsBuilder.fromUriString(url).queryParam(key, value).build().toUri();
UriBuilder
(https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/util/UriBuilder.html)和`UriBuilderFactory`(https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/util/UriBuilderFactory.html)。 - Brice Roncace现在是2022年,有一款非常流行的库叫做OkHttp,已经在 GitHub 上获得了41K次点赞。使用这个库,你可以构建如下的 URL:
import okhttp3.HttpUrl;
URL url = new HttpUrl.Builder()
.scheme("http")
.host("example.com")
.port(4567)
.addPathSegments("foldername/1234")
.addQueryParameter("abc", "xyz")
.build().url();
addPathSegment
(而不是 addPathSegments
)。 - PapaFreud因为建议使用URL类而受到责备。我会采纳评论者的建议,建议使用URI类。我建议您仔细查看URI的构造函数,因为一旦创建,该类非常不可变。
我认为这个构造函数允许您设置URI中可能需要的所有内容。
URI(String scheme, String userInfo, String host, int port, String path, String query, String fragment)
Constructs a hierarchical URI from the given components.
org.apache.httpcomponents.core5:httpcore5:5.2.1
,然后:URI uri = new URIBuilder("http://yourapi.com/rest")
.addParameter("count", "5")
.addParameter("filter", "full text search")
.build();