問題
測試接口用的工具是SoapUI,可以在Request Properties中填入Username和Password用于請求驗證,但在代碼中使用的是基于Hutool的SoapClient工具尤泽。
看了SoapClient內(nèi)部實現(xiàn)歌逢,沒有找到可以在哪里設(shè)置Basic Authentication驗證巾钉。
Request Properties.png
解決
在網(wǎng)上查看相關(guān)資料發(fā)現(xiàn)2種方式
- 在Http請求頭上添加Basic Authentication認證
- 使用Authenticator重寫getPasswordAuthentication()
在Http請求頭上添加Basic Authentication認證
// httpConn 方式
httpConn.setRequestProperty("Authorization", "Basic " + Base64.encodeBase64String("username:password".getBytes()));
// httpPost 方式
httpPost.addHeader("Authorization", "Basic " + Base64.encodeBase64String("username:password".getBytes()));
使用Authenticator重寫getPasswordAuthentication()
在 SoapClient 中找了很長時間也沒發(fā)現(xiàn)可以在哪里設(shè)置請求頭,只好使用此方式秘案!
// http 證授權(quán)方式
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
// 過濾指定域名授權(quán)
if (this.getRequestingURL().toString().indexOf("www.reibang.com") > 0) {
// basic 授權(quán)
return new PasswordAuthentication(username, password.toCharArray());
}
return null;
}
});
// 初始接口客戶端-hutool工具
SoapClient soapClient = this.create(url,
"urn:ZzzzzzList", "urn:sap-com:document:sap:soap:functions:mc-style"
);
進展
- 2020-05-21 已經(jīng)在Gitee上向Hutool提交Issues
- 2020-06-27 在新版本5.3.6增加支持