我正在尝试使用具有基本授权的处理程序调用 SOAP Web 服务,但 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 并手动添加 Authorziation header (调试期间代码中的值)时,我收到了来自端点的响应,但使用代码它现在失败了。
任何指针都会非常有帮助。谢谢
最佳答案
您需要将代码更改为如下所示:
@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你应该使用 sun.misc.BASE64Encoder()
中的 Base64Coder
来编码 authString
此外,您应该始终从此方法返回 true
,否则您将通过返回 false
来阻止处理程序请求链的处理。
关于java - 具有基本身份验证的 JAX-WS 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53673619/