问题

测试接口用的工具是 SoapUI,可以在 Request Properties 中填入 Username 和 Password 用于请求验证,但在代码中使用的是基于 Hutool 的 SoapClient 工具。
看了 SoapClient 内部实现,没有找到可以在哪里设置 Basic Authentication 验证。
Soap Basic Authentication 基础认证 - 图1

解决

在网上查看相关资料发现2种方式

  • 在Http请求头上添加 Basic Authentication 认证
  • 使用 Authenticator 重写 getPasswordAuthentication()

    在Http请求头上添加Basic Authentication认证

    1. // httpConn 方式
    2. httpConn.setRequestProperty("Authorization", "Basic " + Base64.encodeBase64String("username:password".getBytes()));
    3. // httpPost 方式
    4. httpPost.addHeader("Authorization", "Basic " + Base64.encodeBase64String("username:password".getBytes()));

    使用Authenticator重写getPasswordAuthentication()

    在 SoapClient 中找了很长时间也没发现可以在哪里设置请求头,只好使用此方式!

    1. // http 证授权方式
    2. Authenticator.setDefault(new Authenticator() {
    3. @Override
    4. protected PasswordAuthentication getPasswordAuthentication() {
    5. // 过滤指定域名授权
    6. if (this.getRequestingURL().toString().indexOf("www.jianshu.com") > 0) {
    7. // basic 授权
    8. return new PasswordAuthentication(username, password.toCharArray());
    9. }
    10. return null;
    11. }
    12. });
    13. // 初始接口客户端-hutool工具
    14. SoapClient soapClient = this.create(url,
    15. "urn:ZzzzzzList", "urn:sap-com:document:sap:soap:functions:mc-style"
    16. );

    进展

  • 2020-05-21 已经在Gitee上向Hutool提交Issues

  • 2020-06-27 在新版本5.3.6增加支持

    参考

  • java-web-service-client-basic-authentication

  • 对于Webservice SOAP请求中,需要进行Basic认证和动态获取用户名密码办法
  • HttpURLConnection安全认证式访问方法
  • java发送带Basic Auth认证的http post请求实例代码