问题
测试接口用的工具是 SoapUI,可以在 Request Properties 中填入 Username 和 Password 用于请求验证,但在代码中使用的是基于 Hutool 的 SoapClient 工具。
看了 SoapClient 内部实现,没有找到可以在哪里设置 Basic Authentication 验证。
解决
在网上查看相关资料发现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 中找了很长时间也没发现可以在哪里设置请求头,只好使用此方式!
// http 证授权方式
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
// 过滤指定域名授权
if (this.getRequestingURL().toString().indexOf("www.jianshu.com") > 0) {
// basic 授权
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 已经在Gitee上向Hutool提交Issues
-
参考
- 对于Webservice SOAP请求中,需要进行Basic认证和动态获取用户名密码办法
- HttpURLConnection安全认证式访问方法
- java发送带Basic Auth认证的http post请求实例代码