Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

url

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

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.

like image 275
jon077 Avatar asked May 19 '09 14:05

jon077


People also ask

What is a URI in Java?

A URI is a uniform resource identifier while a URL is a uniform resource locator. Hence every URL is a URI, abstractly speaking, but not every URI is a URL. This is because there is another subcategory of URIs, uniform resource names (URNs), which name resources but do not specify how to locate them.

How do I find the URL URI?

The getURI() function of URL class converts the URL object to a URI object. Any URL which compiles with RFC 2396 can be converted to URI. URLs which are not in the specified format will generate an error if converted to URI format.

What is URI in spring boot?

Uniform Resource Identifier (URI) − a sequence of characters that allows the complete identification of any abstract or physical resource.

What is a URI kotlin?

kotlin.Any. ↳ java.net.URI. Represents a Uniform Resource Identifier (URI) reference.


7 Answers

As of Apache HTTP Component HttpClient 4.1.3, from the official 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=
}
}

Edit: as of v4.2 URIUtils.createURI() has been deprecated in favor of 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());
like image 123
Chikei Avatar answered Oct 05 '22 08:10

Chikei


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

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

like image 28
Mikael Gueck Avatar answered Oct 05 '22 06:10

Mikael Gueck


Apache HTTPClient?

like image 22
takete.dk Avatar answered Oct 05 '22 06:10

takete.dk


Using HTTPClient worked well.

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

}
like image 24
jon077 Avatar answered Oct 05 '22 07:10

jon077


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


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

See also: GIST > URI Builder Tests

like image 22
Nick Grealy Avatar answered Oct 05 '22 08:10

Nick Grealy


Use OkHttp

It's 2022 and there is a very popular library named OkHttp which has been starred 41K times on GitHub. With this library, you can build an url like below:

import okhttp3.HttpUrl;

URL url = new HttpUrl.Builder()
    .scheme("http")
    .host("example.com")
    .port(4567)
    .addPathSegments("foldername/1234")
    .addQueryParameter("abc", "xyz")
    .build().url();
like image 44
Tyler Liu Avatar answered Oct 05 '22 08:10

Tyler Liu


After being lambasted for suggesting the URL class. I will take the commenter's advice and suggest the URI class instead. 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.

URI(String scheme, String userInfo, String host, int port, String path, String query, String fragment)
          Constructs a hierarchical URI from the given components.
like image 25
Mike Pone Avatar answered Oct 05 '22 06:10

Mike Pone