Tuesday 29 January 2013

Grails plugin: REST facilities set timeout on withHttp

One of my tasks at my work currently is to implement a timeout on web service calls we make. We currently use the withHttp closure to make our calls inside of our Grails projects. This handy call is nice but unfortunately it doesn't have any options to set the default timeout. To set the timeout, you will have to do the following:

  withHttp(uri: host )
  {
   def client = getClient()
   client.setHttpRequestRetryHandler( new DefaultHttpRequestRetryHandler(1, true) )
   def httpParams = client.getParams()
   httpParams.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, TIMEOUT)
   httpParams.setParameter(CoreConnectionPNames.SO_TIMEOUT, TIMEOUT)
   
   handler.failure = { resp ->
    return new Response(resp)
   }
   
   request( GET, XML ) {  req ->   
    
    response.success = { resp ->
     def payload = resp?.entity?.content?.text
     rr = new Response(resp)
    }
   }
  }
Notice that we are also setting the retry count = 1
DefaultHttpRequestRetryHandler(int retryCount, boolean requestSentRetryEnabled)
Also notice that in addition to setting the connection timeout, we also should set the socket timeout (otherwise weird exceptions will occur if there's a problem).

No comments:

Post a Comment