XmlSlurper.parse(uri) with HTTP basic authentication
Asked Answered
H

2

12

I need to grab a data from XML-RPC web-service.

new XmlSlurper().parse("http://host/service") works fine, but now I have a particular service that requires basic HTTP authentication.

How can I set username and password for parse() method, or modify HTTP headers of the request?

Using http://username:password@host/service doesn't help - I still get java.io.IOException: Server returned HTTP response code: 401 for URL exception.

Thanks

Hylan answered 7/2, 2011 at 22:30 Comment(0)
C
22

I found this code over here which might help?

Editing this code to your situation, we get:

def addr       = "http://host/service"
def authString = "username:password".getBytes().encodeBase64().toString()

def conn = addr.toURL().openConnection()
conn.setRequestProperty( "Authorization", "Basic ${authString}" )
if( conn.responseCode == 200 ) {
  def feed = new XmlSlurper().parseText( conn.content.text )

  // Work with the xml document

} else {
  println "Something bad happened."
  println "${conn.responseCode}: ${conn.responseMessage}" 
}
Clamworm answered 8/2, 2011 at 7:56 Comment(0)
T
3

This will work for you

Please remember to use this instead of the 'def authString' mentioned above:

def authString  = "${usr}:${pwd}".getBytes().encodeBase64().toString()
Torruella answered 6/6, 2012 at 12:31 Comment(1)
I defined my parameters as usr and pwd. Cheers!Torruella

© 2022 - 2024 — McMap. All rights reserved.