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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/883136/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 20:38:49  来源:igfitidea点击:

What is the idiomatic way to compose a URL or URI in Java?

javaurl

提问by jon077

How do I build a URL or a URI in Java? Is there an idiomatic way, or libraries that easily do this?

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

I need to allow starting from a request string, parse/change various URL parts (scheme, host, path, query string) and support adding and automatically encoding query parameters.

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

采纳答案by jon077

Using HTTPClient worked well.

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

}

回答by Mikael Gueck

As the author, I'm probably not the best person to judge if my URL/URI builder is good, but here it nevertheless is: https://github.com/mikaelhg/urlbuilder

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

I wanted the simplest possible complete solution with zero dependencies outside the JDK, so I had to roll my own.

我想要一个在 JDK 之外零依赖的最简单的完整解决方案,所以我不得不推出自己的解决方案。

回答by Mike Pone

After being lambasted for suggesting the URL class. I will take the commenter's advice and suggest the URI classinstead. I suggest you look closely at the constructors for a URI as the class is very immutable once created.
I think this constructor allows you to set everything in the URI that you could need.

在因为建议 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.

回答by Chikei

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

从 Apache HTTP 组件 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=
}
}

Edit: as of v4.2 URIUtils.createURI()has been deprecated in favor of URIBuilder:

编辑:从 v4.2URIUtils.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());

回答by Nick Grealy

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

有很多库可以帮助您构建 URI(不要重新发明轮子)。这里有三个让你开始:



Java EE 7

Java EE 7

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


org.apache.httpcomponents:httpclient:4.5.2

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

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

另请参阅:GIST > URI Builder 测试

回答by Tyler Long

Use OkHttp

使用 OkHttp

It's 2020and there is a very popular library named OkHttpwhich has been starred 35Ktimes on GitHub. With this library, you can build an url like below:

现在是2020 年,有一个名为OkHttp的非常受欢迎的库,它在 GitHub 上已被加星35K次。使用此库,您可以构建如下所示的 url:

import okhttp3.HttpUrl;

URL url = new HttpUrl.Builder()
    .scheme("http")
    .host("example.com")
    .port(4567)
    .addPathSegment("foldername/1234")
    .addQueryParameter("abc", "xyz")
    .build().url();