Constructing and modifying complex URLs

At the heart of any HTTP request, there is a Universal Resource Locator (URL) or a more generic Universal Resource Identifier (URI) which identifies the target of the operation we need to perform.

We have seen in the previous recipes (for example, the Downloading content from the Internet recipe) that it's very hard to avoid dealing with URLs when interacting with the HTTP protocol. In this recipe, we are going to present a more structured approach to constructing and modifying complex URLs with the help of an additional Groovy library.

How to do it...

If you have worked with Java's URL class before, you know that the only way to construct instances of that class is to provide a full URL to the constructor, which will return an immutable (non-changeable) object.

Groovy's core does not add any special support for URL manipulation apart from what Java already offers, but there is an officially supported HttpBuilder module that is hosted on Groovy's website (http://groovy.codehaus.org/modules/http-builder) and that can be used to make more accessible URL creation and modification:

  1. First of all, we need to @Grab that module and import the URIBuilder class, which will help us with our task:
    @Grab(
      group='org.codehaus.groovy.modules.http-builder',
      module='http-builder',
      version='0.6'
    )
    import groovyx.net.http.URIBuilder
  2. At this point, we can create a URIBuilder instance and pass baseUri to that:
    def baseUri =
          'http://groovy.services.com/service1/operation2'
    def uri = new URIBuilder(baseUri)
  3. Now, we can modify any URI's component with simple property assignments, as follows:
    uri.with {
      scheme = 'https'
      host = 'localhost'
      port = 8080
      fragment = 'some_anchor'
      path = 'some_folder/some_page.html'
      query = [param1: 2, param2: 'x']
    }
  4. With the information passed to URIBuilder, we can create URI, URL, or String instances at any point:
    uri.toURI()
    uri.toURL()
    uri.toString()

How it works...

Internally the URIBuilder class stores all URI components such as, scheme (http:// and https://), user information (username:password), host, port, path, and fragment separately. This allows creating new URLs incrementally and changing existing URLs without a need to write custom string parsing/concatenating logic.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.14.39.59