代码之家  ›  专栏  ›  技术社区  ›  lesnar

具有基本身份验证的JAX-WS请求

  •  3
  • lesnar  · 技术社区  · 6 年前

    我试图使用具有基本授权的处理程序调用SOAP WebService,但不知何故API使用401未授权进行响应。

    @Override
    public boolean handleMessage(SOAPMessageContext context) {
        Boolean outboundProperty = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
        if (outboundProperty.booleanValue()) {
            String authString = parameter.getUser() + ":" + parameter.getPassword();
            try {
                 Map<String, List<String>> headers = (Map<String, List<String>>)
                         context.get(MessageContext.HTTP_REQUEST_HEADERS);
    
                 if (null == headers) {
                     headers = new HashMap<String, List<String>>();
                 }
    
                 headers.put("Authorization", Collections.singletonList(
                     "Basic " + new String(Base64.encode(authString.getBytes()))));
            } catch(Exception e) {
                log4j.error(e.getMessage(), e);
            }
        }
        return outboundProperty;
    }
    

    当我使用SOAP UI并手动添加authorization头(调试期间代码中的值)时,我从端点接收响应,但使用的代码到现在为止失败了。

    任何提示都会很有帮助。谢谢

    1 回复  |  直到 6 年前
        1
  •  2
  •   Mohsen    6 年前

    您需要将代码更改为如下所示:

    @Override
    public boolean handleMessage(SOAPMessageContext context) {
        Boolean outboundProperty = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
        if(outboundProperty.booleanValue()){
            try{
                String authString = parameter.getUser() + ":" + parameter.getPassword();
                SOAPMessage soapMessage =context.getMessage();
                String authorization = new sun.misc.BASE64Encoder().encode(authString.getBytes());
                soapMessage.getMimeHeaders().addHeader("Authorization","Basic " + authorization);   
                soapMessage.saveChanges(); 
            }catch(Exception e){
                log4j.error(e.getMessage(), e);
            }
        }
        return true;
    }
    

    更新时间:

    如所解释的 here 你应该使用 Base64Coder sun.misc.BASE64Encoder() 用于编码 authString

    你也应该一直回来 true 否则,您将通过返回 false .