Using Groovy's HTTPBuilder, how do you set timeouts

Steve s. picture Steve s. · Feb 25, 2016 · Viewed 8.3k times · Source

I'm trying to set a connection timeout with Groovy HTTPBuilder and for the life of me can't find a way.

Using plain ol' URL it's easy:

def client = new URL("https://search.yahoo.com/search?q=foobar")
def result = client.getText( readTimeout: 1 )

This throws a SocketTimeoutException, but that's not quite what I want. For a variety of reasons, I'd rather use HTTPBuilder or better RESTClient.

This does work:

    def client = new HTTPBuilder()
    def result = client.request("https://search.yahoo.com/", Method.GET, "*/*") { HttpRequest request ->
        uri.path = "search"
        uri.query = [q: "foobar"]
        request.getParams().setParameter("http.socket.timeout", 1);
    }

However request.getParams() has been deprecated.

For the life of me I can't find a way to inject a proper RequestConfig into the builder.

Answer

jerryb picture jerryb · Mar 13, 2016

Try this, I'm using 0.7.1:

import groovyx.net.http.HTTPBuilder
import org.apache.http.client.config.RequestConfig
import org.apache.http.config.SocketConfig
import org.apache.http.conn.ConnectTimeoutException
import org.apache.http.impl.client.HttpClients

def timeout = 10000 // millis
SocketConfig sc = SocketConfig.custom().setSoTimeout(timeout).build()
RequestConfig rc = RequestConfig.custom().setConnectTimeout(timeout).setSocketTimeout(timeout).build()
def hc = HttpClients.custom().setDefaultSocketConfig(sc).setDefaultRequestConfig(rc).build()        
def http = new HTTPBuilder('https://search.yahoo.com/')
http.client = hc

http.get(path:'/search')