根据业务(Soap 请求第三方Ws接口,Header 进行身份验证),中于系统中取得的header 部分 是map键值对:
HashMap<String,Object> map =new HashMap<>();
map.put("headers.authElement.userId.asd.as.zxc.zx","zhang");
map.put("headers.authElement.userPass","123");
第三方接口需要的格式为:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ws="http://ws.cdyne.com/">
<soapenv:Header>
<authElement>
<userId>aa</userId>
<userPass>123</userPass>
</authElement>
</soapenv:Header>
<soapenv:Body>
<ws:sayHi>
<!--Optional:-->
<ws:name>2</ws:name>
</ws:sayHi>
</soapenv:Body>
</soapenv:Envelope>
贴代码:
public static void main(String[] args) {
HashMap<String,Object> map =new HashMap<>();
map.put("headers.authElement.userId.asd.as.zxc.zx","zhang");
map.put("headers.authElement.userPass","123");
System.err.println(new SoapProtocol().formatSOAPHeader(map));
}
public String formatSOAPHeader(HashMap<String,Object> map){
Iterator<Map.Entry<String,Object>> iterator = map.entrySet().iterator();
StringBuffer sb = new StringBuffer();
Document wsDocument = DocumentHelper.createDocument();
Element root=wsDocument.addElement("SOAP-ENV:Header");
while(iterator.hasNext()){
Map.Entry<String,Object> entry = iterator.next();
String key = entry.getKey();
String value = entry.getValue().toString();
String[] splitKey = key.split("\\.");
joinHeader(splitKey,value,root);
}
return wsDocument.getRootElement().asXML();
}
Element joinHeader(String[] splitKey,String value,Element root){
for(int i=1;i<splitKey.length;i++){
if(StringUtil.getChildElements(root,splitKey[i])==null){
Element element = root.addElement(splitKey[i]);
if(i==splitKey.length-1){
element.addText(value);
}else{
root=element;
}
}else{
root=root.element(splitKey[i]);
}
}
return root;
}