Class HttpClient


  • public class HttpClient
    extends Object
    This class can be used to run HTTP requests. At construction it takes a URL. You may configure the client further by setting the HTTP method (default GET) and adding headers and query parameters (if you didn't include them in the URL). After that there are various methods to write data (optional) and finally to get the response and read data. When you no longer need the client, you should call close().

    It assumes that the server returns response code 200 OK on success. For any other response code (including 3xx redirects) it throws a HttpClientException.

    Any strings will be read and written as UTF-8.

    • Constructor Detail

      • HttpClient

        public HttpClient​(String url)
        Constructs a new HTTP client. If you want to use query parameters in the HTTP request, you can specify the URL without query parameters and then call addQueryParam(). Alternatively you can include the query parameters in the URL.
        Parameters:
        url - the URL
    • Method Detail

      • close

        public void close()
        Closes this client. You should always call this method when you no longer need the client.
      • setMethod

        public HttpClient setMethod​(String method)
        Sets the HTTP method. The default is GET.
        Parameters:
        method - the HTTP method
        Returns:
        this client (so you can chain method calls)
      • addQueryParam

        public HttpClient addQueryParam​(String name,
                                        String value)
        Adds a query parameter. This will be appended to the request URL. You should only call this method if you didn't include query parameters in the URL at construction.
        Parameters:
        name - the parameter name
        value - the parameter value
        Returns:
        this client (so you can chain method calls)
      • setQueryParams

        public HttpClient setQueryParams​(Map<String,​String> params)
        Sets a map with query parameters. They will be appended to the request URL. You should only call this method if you didn't include query parameters in the URL at construction. This method overwrites any parameters you have added with addQueryParam().
        Parameters:
        params - the query parameters
        Returns:
        this client (so you can chain method calls)
      • addHeader

        public HttpClient addHeader​(String name,
                                    String value)
        Adds a header to the HTTP request. Note that some of the write methods can automatically set the Content-Type header, so you don't need to specify it here.
        Parameters:
        name - the header name
        value - the header value
        Returns:
        this client (so you can chain method calls)
      • setHeaders

        public HttpClient setHeaders​(Map<String,​String> headers)
        Sets a map with the HTTP headers. Note that some of the write methods can automatically set the Content-Type header, so you don't need to specify it here. This method overwrites any headers you have added with addHeader().
        Parameters:
        headers - the headers
        Returns:
        this client (so you can chain method calls)
      • getUrl

        public String getUrl()
        Returns the URL including query parameters.
        Returns:
        the URL including query parameters
      • getOutputStream

        public OutputStream getOutputStream()
                                     throws IOException
        Returns the output stream to write data to the HTTP content. Before calling this method you must have configured the client (method, headers, query parameters). This method will initialise the connection and open the output stream if that wasn't done yet. The output stream will be closed automatically when you read the response.
        Returns:
        the output stream
        Throws:
        IOException - if an error occurs while communicating with the HTTP server
      • getWriter

        public Writer getWriter()
                         throws IOException
        Returns a writer to write data to the HTTP content. Before calling this method you must have configured the client (method, headers, query parameters). This method will initialise the connection and open the output if that wasn't done yet. The writer will be closed automatically when you read the response.
        Returns:
        the writer
        Throws:
        IOException - if an error occurs while communicating with the HTTP server
      • writePostParam

        public HttpClient writePostParam​(String name,
                                         String value)
                                  throws IOException
        Writes a POST parameter to the HTTP content. It writes POST parameters as a URL-encoded parameter string. Before calling this method you must have configured the client (method, headers, query parameters). This method will initialise the connection, set header Content-Type to application/x-www-form-urlencoded, and open the output if that wasn't done yet. You can repeat this method for multiple parameters. The output will be closed automatically when you read the response.
        Parameters:
        name - the parameter name
        value - the parameter value
        Returns:
        this client (so you can chain method calls)
        Throws:
        IOException - if an error occurs while communicating with the HTTP server
      • writeJson

        public HttpClient writeJson​(Object obj)
                             throws IOException
        Writes the specified object as a JSON string using the Jackson ObjectMapper. Before calling this method you must have configured the client (method, headers, query parameters). This method will initialise the connection, set header Content-Type to application/json, and open the output if that wasn't done yet. The output will be closed automatically when you read the response.
        Parameters:
        obj - the object
        Returns:
        this client (so you can chain method calls)
        Throws:
        IOException - if a writing error occurs
      • writeString

        public HttpClient writeString​(String content)
                               throws IOException
        Writes a string to the HTTP content. Before calling this method you must have configured the client (method, headers, query parameters). Include header Content-Type (for example "text/plain; charset=UTF-8"). This method will initialise the connection and open the output if that wasn't done yet. You can repeat this method if you want to write more. The output will be closed automatically when you read the response.
        Parameters:
        content - the string content
        Returns:
        this client (so you can chain method calls)
        Throws:
        IOException - if an error occurs while communicating with the HTTP server
      • writeBytes

        public HttpClient writeBytes​(byte[] bs)
                              throws IOException
        Writes a byte array to the HTTP content. Before calling this method you must have configured the client (method, headers, query parameters). Include header Content-Type (for example "application/octet-stream"). This method will initialise the connection and open the output if that wasn't done yet. You can repeat this method if you want to write more. The output will be closed automatically when you read the response.
        Parameters:
        bs - the byte array
        Returns:
        this client (so you can chain method calls)
        Throws:
        IOException - if an error occurs while communicating with the HTTP server
      • getResponse

        public HttpURLConnection getResponse()
                                      throws HttpClientException,
                                             IOException
        Gets the HTTP response and then returns the HTTP connection from which details about the response can be obtained. You should call this method after configuring the client (method, headers, query parameters) and optionally writing data. This method will initialise the connection, get the response and open the input if that wasn't done yet.

        If the response code is not 200 OK, it throws a HttpClientException. For response codes 4xx or 5xx, the exception will contain the content of the error stream.

        This class has methods to read data from the response, which you can call instead of or along with this method.

        Returns:
        the HTTP connection
        Throws:
        HttpClientException - if the HTTP request returned an error response
        IOException - if an error occurs while communicating with the HTTP server
      • getInputStream

        public InputStream getInputStream()
                                   throws HttpClientException,
                                          IOException
        Returns the input stream to read data from the HTTP response. You should call this method after configuring the client (method, headers, query parameters) and optionally writing data. This method will initialise the connection, get the response and open the input stream if that wasn't done yet.

        If the response code is not 200 OK, it throws a HttpClientException. For response codes 4xx or 5xx, the exception will contain the content of the error stream.

        Returns:
        the input stream
        Throws:
        HttpClientException - if the HTTP request returned an error response
        IOException - if an error occurs while communicating with the HTTP server
      • getReader

        public Reader getReader()
                         throws HttpClientException,
                                IOException
        Returns the reader to read data from the HTTP response. You should call this method after configuring the client (method, headers, query parameters) and optionally writing data. This method will initialise the connection, get the response and open the input if that wasn't done yet.

        If the response code is not 200 OK, it throws a HttpClientException. For response codes 4xx or 5xx, the exception will contain the content of the error stream.

        Returns:
        the reader
        Throws:
        HttpClientException - if the HTTP request returned an error response
        IOException - if an error occurs while communicating with the HTTP server
      • readString

        public String readString()
                          throws HttpClientException,
                                 IOException
        Reads the HTTP response as a string. You should call this method after configuring the client (method, headers, query parameters) and optionally writing data. This method will initialise the connection, get the response and open the input if that wasn't done yet.
        Returns:
        the response string
        Throws:
        HttpClientException - if the HTTP request returned an error response
        IOException - if an error occurs while communicating with the HTTP server
      • readJson

        public <T> T readJson​(Class<T> clazz)
                       throws HttpClientException,
                              ParseException,
                              IOException
        Reads the HTTP response as a JSON string and converts it to an object of the specified class using the Jackson ObjectMapper. You should call this method after configuring the client (method, headers, query parameters) and optionally writing data. This method will initialise the connection, get the response and open the input if that wasn't done yet.
        Type Parameters:
        T - the type of object to return
        Parameters:
        clazz - the result class
        Returns:
        the result object
        Throws:
        HttpClientException - if the HTTP request returned an error response
        ParseException - if a JSON parsing error occurs
        IOException - if an error occurs while communicating with the HTTP server
      • readJson

        public <T> T readJson​(com.fasterxml.jackson.core.type.TypeReference<T> typeRef)
                       throws HttpClientException,
                              ParseException,
                              IOException
        Reads the HTTP response as a JSON string and converts it to an object of the specified result type using the Jackson ObjectMapper. You should call this method after configuring the client (method, headers, query parameters) and optionally writing data. This method will initialise the connection, get the response and open the input if that wasn't done yet.

        If you want to convert to MyObject, you can specify:
        new TypeReference<MyObject>() {}

        Type Parameters:
        T - the type of object to return
        Parameters:
        typeRef - the result type
        Returns:
        the result object
        Throws:
        HttpClientException - if the HTTP request returned an error response
        ParseException - if a JSON parsing error occurs
        IOException - if an error occurs while communicating with the HTTP server
      • readBytes

        public byte[] readBytes()
                         throws HttpClientException,
                                IOException
        Reads the HTTP response as a byte array. You should call this method after configuring the client (method, headers, query parameters) and optionally writing data. This method will initialise the connection, get the response and open the input if that wasn't done yet.
        Returns:
        the response bytes
        Throws:
        HttpClientException - if the HTTP request returned an error response
        IOException - if an error occurs while communicating with the HTTP server
      • getResponseHeaders

        public Map<String,​String> getResponseHeaders()
        Returns the response headers. You can call this after reading the response. All header names will be in lower case.
        Returns:
        the response headers