HTTP Request in Grails

Posted: Thu, Mar 24 04:39 AM (PDT)

Simple function how you can make HTTP request in Grails

def httpPostRequest(String address, String data, String referer = "http://www.google.com", method = "POST", userAgent = "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13") {
	method = method?.toString()?.toUpperCase()
	if (method != "GET") { method = "POST" }
	try {
		def url = new URL(address)
		def conn = url.openConnection()
		conn.setRequestMethod(method)
		conn.setRequestProperty("User-Agent", userAgent)
		conn.setRequestProperty("Referer", referer)
		conn.doOutput = true
		Writer wr = new OutputStreamWriter(conn.outputStream)
		wr.write(data)
		wr.flush()
		wr.close()
		conn.connect()
		return conn?.content?.text
	} catch (e) {
		println e
		return false
	}
}

Now, try to use our function

def content = httpPostRequest("http://www.atlas365.com", "test=my%20first%20test")
if (content) { println content } else { println "Error!" }

This example show us "How we can get the web page http://www.atlas365.com/ by POST request with test parameter". The test parameter is equal "my first test"

Tags: