2011-02-07 118 views
9

我需要從XML-RPC web服務中獲取數據。帶HTTP基本認證的XmlSlurper.parse(uri)

new XmlSlurper().parse("http://host/service")工作正常,但現在我有一個特定的服務,需要基本的HTTP身份驗證。

如何爲parse()方法設置用戶名和密碼,或修改請求的HTTP標頭?

使用http://username:[email protected]/service沒有幫助 - 我仍然得到java.io.IOException: Server returned HTTP response code: 401 for URL異常。

感謝

回答

17

我發現this code over here這可能幫助?

編輯這段代碼到你的情況,我們得到:

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}" 
} 
2

這會爲你工作

請記得用的,而不是「高清authString」上面提到的這一點:

def authString = "${usr}:${pwd}".getBytes().encodeBase64().toString() 
+0

我將我的參數定義爲usr和pwd。乾杯! – Megha 2012-06-06 12:32:25