Using Groovy's HTTPBuilder, how do you set timeouts
Asked Answered
P

4

9

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.

Parvati answered 25/2, 2016 at 19:5 Comment(3)
Have you tried: client.client.params.setParameter("http.socket.timeout", 1000)Burseraceous
Needed this recently myself and came across this: gist.github.com/axeda/5189102Hindemith
Setting a parameter works fine. However, that method has been deprecated. It seems HTTPBuilder hasn't been modernized.Parvati
P
7

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 site = 'https://search.yahoo.com/'
def http = new HTTPBuilder(site)
http.client = hc

# eg. usage
http.get(path:'/search')
Pitching answered 12/3, 2016 at 23:24 Comment(2)
Is it safe to assume timeout is in millis? The docs do not say. :(Oblige
Yes its millis.Pitching
L
1

pure HTTPBuilder:

import org.apache.http.client.config.RequestConfig

def TIMEOUT = 10000
def defaultRequestConfig = RequestConfig.custom()
        .setConnectionRequestTimeout(TIMEOUT)
        .setConnectTimeout(TIMEOUT)
        .setSocketTimeout(TIMEOUT)
        .build()
def client = new HTTPBuilder("uri")
client.setClient(HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build())

RESTClient with everything:

import org.apache.http.auth.AuthScope
import org.apache.http.auth.UsernamePasswordCredentials
import org.apache.http.client.config.RequestConfig
import org.apache.http.conn.ssl.NoopHostnameVerifier
import org.apache.http.conn.ssl.SSLConnectionSocketFactory
import org.apache.http.conn.ssl.TrustSelfSignedStrategy
import org.apache.http.impl.client.BasicCredentialsProvider
import org.apache.http.impl.client.HttpClients
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager
import org.apache.http.ssl.SSLContextBuilder

def restClient = new RESTClient("hostname")

//timeout
def TIMEOUT = 5000
def defaultRequestConfig = RequestConfig.custom()
        .setConnectionRequestTimeout(TIMEOUT)
        .setConnectTimeout(TIMEOUT)
        .setSocketTimeout(TIMEOUT)
        .build()

//basic user/password authentication
def credentials = new UsernamePasswordCredentials("admin", "password")
def credentialsProvider = new BasicCredentialsProvider()
credentialsProvider.setCredentials(AuthScope.ANY, credentials)

//set ssl trust all, no ssl exceptions
def sslContext = new SSLContextBuilder().loadTrustMaterial(null, TrustSelfSignedStrategy.INSTANCE).build()
def sslSocketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE)

//multithreaded connection manager
def multithreadedConnectionManager = new PoolingHttpClientConnectionManager()

//build client with all this stuff
restClient.setClient(HttpClients.custom()
        .setConnectionManager(multithreadedConnectionManager)
        .setDefaultCredentialsProvider(credentialsProvider)
        .setDefaultRequestConfig(defaultRequestConfig)
        .setSSLSocketFactory(sslSocketFactory)
        .build())
Larch answered 16/8, 2018 at 18:42 Comment(0)
T
0

From the JavaDoc, it appears you do it by using AsyncHttpBuilder instead? That class extends HTTPBuilder and it has a setTimeout(int) method.

Look at this: http://www.kellyrob99.com/blog/2013/02/10/groovy-and-http/ According to that, it appears you might be able to follow the advice here to get a timeout on your connection: Java HTTP Client Request with defined timeout

Touchdown answered 25/2, 2016 at 19:25 Comment(7)
Thanks, good idea. However, I looked at the code for AsyncHTTPBuilder. It also uses the deprecated method of setting params. I guess there's no better way.Parvati
Ok, i added a url to my answer. Maybe that will help.Touchdown
Thanks again, but the issue isn't about getting it to work - the timeout setting is fine. The issue is that AsyncHTTPBuilder is using deprecated methods. Check out line 211 code . client.getParams() is deprecated.Parvati
I sorta see what you mean here: hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/…Touchdown
Yeah - you got it, djangofan. Actually, I'm getting concerned as it seems HTTPBuilder might be a dead project.Parvati
I'm surprised the latest Groovy still uses that library. Maybe there is a reason for it. NO answer was given to this question: github.com/jgritman/httpbuilder/issues/57Touchdown
It appears you MIGHT be able to get around the deprecation by using this method? #15336977Touchdown
A
-1

I use like this

def timeOut = 10000
HTTPBuilder http = new HTTPBuilder('http://url.com')
http.client.params.setParameter('http.connection.timeout', new Integer(timeOut))
http.client.params.setParameter('http.socket.timeout', new Integer(timeOut))
Aixlachapelle answered 8/2, 2017 at 12:11 Comment(1)
This still uses getParams(), which OP does not want to use because it's deprecated.Florentinaflorentine

© 2022 - 2024 — McMap. All rights reserved.