john Smith
john Smith

Reputation: 17906

Grails/Groovy URL .getText receive status

I'm including some wordpress contents to my grails app with a customTag everything works fine.Now i want to render some standard-text if the url's status-code is not 200 OK

i have this so far

def wordpressHp = { body ->
//  def url = grailsApplication.config.wordpress.server.url+'?include=true'
    def url = "http://www.dasdasdasgsdniga.nd"
    def content 
    try{
        content = url.toURL().getText(connectTimeout: 10000)
    }catch(e){
        content="SORRY WORDPRESS IS CURRENTLY NOT AVAILABLE"
    }
    out << content
}

The correct url is commented out, i now expect the try to fail.
But instead of faling it's rendering some dns-error page of my provider. So i think i have to look for http-status code, but how do i do that ?

for any hint, thanks in advance

Upvotes: 6

Views: 5911

Answers (1)

tim_yates
tim_yates

Reputation: 171074

You could try:

def url = "http://www.dasdasdasgsdniga.nd"
def content 
try {
    content = url.toURL().openConnection().with { conn ->
        readTimeout = 10000
        if( responseCode != 200 ) {
            throw new Exception( 'Not Ok' )
        }
        conn.content.withReader { r ->
            r.text
        }
    }
}
catch( e ) {
    content="SORRY WORDPRESS IS CURRENTLY NOT AVAILABLE"
}

Upvotes: 11

Related Questions