代码之家  ›  专栏  ›  技术社区  ›  jon077

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

  •  107
  • jon077  · 技术社区  · 17 年前

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

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

    7 回复  |  直到 9 年前
        1
  •  79
  •   Chin    9 年前

    从Apache HTTP组件HttpClient 4.1.3开始 tutorial :

    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());
    
        2
  •  64
  •   Mikael Gueck    14 年前

    作为作者,我可能不是判断我的URL/URI构建器是否正确的最佳人选 好的 ,但事实上: https://github.com/mikaelhg/urlbuilder

    我想要一个尽可能简单的完整解决方案,在JDK之外没有依赖关系,所以我不得不推出自己的解决方案。

        3
  •  56
  •   takete.dk    17 年前
        4
  •  29
  •   Michael Myers KitsuneYMG    17 年前

    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();
    
    }
    
        5
  •  16
  •   Nick Grealy    9 年前


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

    另见: GIST > URI Builder Tests

        6
  •  14
  •   Saikat SHASHANK HONRAO    5 年前

    它是 2021 还有一个非常受欢迎的图书馆叫 OkHttp 哪部电影已经主演了 40K GitHub上的时报。使用此库,您可以构建如下url:

    import okhttp3.HttpUrl;
    
    URL url = new HttpUrl.Builder()
        .scheme("http")
        .host("example.com")
        .port(4567)
        .addPathSegments("foldername/1234")
        .addQueryParameter("abc", "xyz")
        .build().url();
    
        7
  •  1
  •   Mike Pone    14 年前

    URI class 相反我建议您仔细查看URI的构造函数,因为类一旦创建就非常不可变。

    URI(String scheme, String userInfo, String host, int port, String path, String query, String fragment)
              Constructs a hierarchical URI from the given components.