用 Java 编写 URL 或 URI 的惯用方法是什么?

新手上路,请多包涵

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

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

原文由 jon077 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 434
2 个回答

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

}

原文由 jon077 发布,翻译遵循 CC BY-SA 2.5 许可协议

从 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=
}
}

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

原文由 Chikei 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题