在 Java 中组成 URL 或 URI 的惯用方法是什么?

如何在 Java 中构建 URL 或 URI?有没有一种惯用的方法或者图书馆可以很容易地做到这一点?

我需要允许从请求字符串开始,解析/更改各种 URL 部分(模式、主机、路径、查询字符串) ,并支持添加和自动编码查询参数。

81918 次浏览

使用 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();


}

作为作者,我可能不是判断我的 URL/URI 构建器是否是 很好的最佳人选,但在这里它仍然是: https://github.com/mikaelhg/urlbuilder

我想要一个在 JDK 之外没有任何依赖性的最简单可能的完整解决方案,所以我必须自己动手。

在被斥责建议 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.

As of Apache HTTP Component HttpClient 4.1.3, from the official 教程:

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());

There are plenty of libraries that can help you with URI building (don't reinvent the wheel). Here are three to get you started:


JavaEE7

import javax.ws.rs.core.UriBuilder;
...
return UriBuilder.fromUri(url).queryParam(key, value).build();

HttpComponent: 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();

See also: GIST > URI Builder Tests

使用 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();