Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to code a URL HTTP Get with Groovy considering inaccesible or down servers?
    text
    copied!<p>I am implementing an API call to the MailChimp API in my web application. But this question is valid for any call to an API which accepts a simple HTTP GET. </p> <p>I would like to catch any errors and allow my application to continue without issues even if the API call failed, The mailchimp servers and down, slow or unavailable.</p> <p><a href="http://apidocs.mailchimp.com/api/" rel="nofollow">MailChimp API</a> Returns a serialized JSON Object. This is my code. </p> <pre><code>def listSubscribe = { apiurl, apikey, listid, email -&gt; def url = "${apiurl}?method=listSubscribe&amp;apikey=${apikey}&amp;id=${listid}&amp;email_address=${email}" } try { def url = new URL(listSubscribe(apiUrl,apiKey,listId,email)) return (url.text == 'true') ? true : false } catch (MalformedURLException e) { return false } catch (java.net.UnknownHostException e) { return false } </code></pre> <p>Should I perform any other try/catch? How can I improve my code to make it safer for inaccesible API calls?</p> <h1>Solution</h1> <p>In order to make the call asynchronous and since I am using this code inside a Grails application I created a <a href="http://grails-plugins.github.com/grails-quartz/guide/index.html" rel="nofollow">Quartz Job</a> to execute the service containing the API Call. </p> <pre><code>class MailChimpListSubscribeJob { def mailChimpService def execute(context) { mailChimpService.listSubscribe(context.mergedJobDataMap.get('email')) } } </code></pre> <p>The Service now uses a timeout and catches the generic Exception:</p> <pre><code>class MailChimpService { def grailsApplication def listSubscribe(email_address) { def apiurl = grailsApplication.config.mailchimp.apiUrl def apikey = grailsApplication.config.mailchimp.apiKey def listid = grailsApplication.config.mailchimp.listId listSubscribe(apiurl, apikey, listid, email_address) } def listSubscribe(apiurl, apikey, listid, email) { try { def cmdurl = "${apiurl}?method=listSubscribe&amp;apikey=${apikey}&amp;id=${listid}&amp;email_address=${email}" def url = new URL(cmdurl) def response = url.getText(connectTimeout: 4 * 1000, readTimeout: 4 * 1000) return (response == 'true') ? true : false } catch (MalformedURLException e) { return false } catch (java.net.UnknownHostException e) { return false } catch (Exception e) { return false } } } </code></pre> <p>And inside my controllers:</p> <pre><code>MailChimpListSubscribeJob.triggerNow([email: 'myemail@example.com']) </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload