java调soap接口

来源:互联网 发布:功夫软件 编辑:程序博客网 时间:2024/06/03 16:07
  1. import java.io.BufferedReader;  
  2. import java.io.File;  
  3. import java.io.FileReader;  
  4. import java.io.IOException;  
  5. import java.io.InputStream;  
  6. import java.io.OutputStream;  
  7. import java.net.HttpURLConnection;  
  8. import java.net.URL;  
  9. //需要commons-io的jar包  
  10. import org.apache.commons.io.IOUtils;  
  11. public class testwebservice {  
  12.   
  13. public static void main(String[] args) {  
  14. try {  
  15. soapSpecialConnection();  
  16. catch (Exception e) {e.printStackTrace();}}  
  17.   
  18. public static void soapSpecialConnection() throws Exception{  
  19. String s = new String();  
  20. StringBuilder soapHeader = new StringBuilder();  
  21. //soapUI自动生成的request xml路径,写入传入参数  
  22. File file = new File("d:\\1.xml");  
  23. BufferedReader reader = null;  
  24. try {reader = new BufferedReader(new FileReader(file));  
  25. String tempString = null;  
  26. // 一次读入一行,直到读入null为文件结束  
  27. while ((tempString = reader.readLine()) != null) {  
  28. soapHeader.append(tempString);  
  29. }  
  30. reader.close();  
  31. catch (IOException e) {  
  32. e.printStackTrace();  
  33. finally {  
  34. if (reader != null) {  
  35. try {  
  36. reader.close();  
  37. catch (IOException e1) {}  
  38. }  
  39. }  
  40. System.out.println("soapHeader="+soapHeader);  
  41. //设置soap请求报文的相关属性  
  42. //url从soapUI的request1的RAW标签的POST获取,url中不要有空格  
  43. String url="http://10.60.217.86:9527/dji-hrService/services/HrService.HrServiceHttpSoap11Endpoint/HTTP/1.1";  
  44. URL u = new URL(url);  
  45. HttpURLConnection conn = (HttpURLConnection) u.openConnection();  
  46. conn.setDoInput(true);  
  47. conn.setDoOutput(true);  
  48. conn.setUseCaches(false);  
  49. conn.setDefaultUseCaches(false);  
  50. //Host,Content-Type,SOAPAction从soapUI的request1的RAW标签的Host,Content-Typ,SOAPActione获取  
  51. conn.setRequestProperty("Host""10.60.217.86:9527");  
  52. conn.setRequestProperty("Content-Type""text/xml;charset=UTF-8");  
  53. conn.setRequestProperty("Content-Length", String.valueOf(soapHeader.length()));  
  54. conn.setRequestProperty("SOAPAction""urn:getWorkAttendanceByUidAndDate");  
  55. conn.setRequestMethod("POST");  
  56. //定义输出流  
  57. OutputStream output = conn.getOutputStream();  
  58. if (null != soapHeader) {  
  59. byte[] b = soapHeader.toString().getBytes("utf-8");  
  60. //发送soap请求报文  
  61. output.write(b, 0, b.length);}  
  62. output.flush();  
  63. output.close();  
  64. //定义输入流,获取soap响应报文  
  65. InputStream input = conn.getInputStream();  
  66. //需设置编码格式,否则会乱码  
  67. s=IOUtils.toString(input, "UTF-8");  
  68. input.close();  
  69. System.out.println("输出的xml="+s);}}

  1. package com.lzw.b2b.soap;  
  2.   
  3. import java.io.ByteArrayInputStream;  
  4. import java.io.InputStream;  
  5. import java.util.HashMap;  
  6. import java.util.Iterator;  
  7. import java.util.List;  
  8. import java.util.Map;  
  9. import java.util.Set;  
  10.   
  11. import org.apache.commons.httpclient.HttpClient;  
  12. import org.apache.commons.httpclient.methods.InputStreamRequestEntity;  
  13. import org.apache.commons.httpclient.methods.PostMethod;  
  14. import org.apache.commons.httpclient.methods.RequestEntity;  
  15. import org.dom4j.Attribute;  
  16. import org.dom4j.Document;  
  17. import org.dom4j.DocumentHelper;  
  18. import org.dom4j.Element;  
  19. import org.slf4j.Logger;  
  20. import org.slf4j.LoggerFactory;  
  21.   
  22. public class DynamicSoapclientCall {  
  23.       
  24.     private static Logger logger = LoggerFactory.getLogger(DynamicSoapclientCall.class);  
  25.   
  26.     private String namespace;  
  27.     private String methodName;  
  28.     private String wsdlLocation;  
  29.     private String soapResponseData;  
  30.   
  31.     public DynamicSoapclientCall(String namespace, String methodName, String wsdlLocation) {  
  32.         this.namespace = namespace;  
  33.         this.methodName = methodName;  
  34.         this.wsdlLocation = wsdlLocation;  
  35.     }  
  36.   
  37.     public int invoke(Map<String, String> patameterMap) throws Exception {  
  38.         PostMethod postMethod = new PostMethod(wsdlLocation);  
  39.         String soapRequestData = buildRequestData(patameterMap);  
  40.   
  41.         byte[] bytes = soapRequestData.getBytes("utf-8");  
  42.         InputStream inputStream = new ByteArrayInputStream(bytes, 0, bytes.length);  
  43.         RequestEntity requestEntity = new InputStreamRequestEntity(inputStream,  
  44.                 bytes.length, "application/soap+xml; charset=utf-8");  
  45.         postMethod.setRequestEntity(requestEntity);  
  46.   
  47.         HttpClient httpClient = new HttpClient();  
  48.         int statusCode = httpClient.executeMethod(postMethod);  
  49.         soapResponseData = postMethod.getResponseBodyAsString();  
  50.   
  51.         return statusCode;  
  52.     }  
  53.   
  54.     private String buildRequestData(Map<String, String> patameterMap) {  
  55.         StringBuffer soapRequestData = new StringBuffer();  
  56.         soapRequestData.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");  
  57.         soapRequestData.append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\""  
  58.                              + " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\""  
  59.                              + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">");  
  60.         soapRequestData.append("<soapenv:Body>");  
  61.         soapRequestData.append("<" + methodName + " xmlns=\"" + namespace + "\">");  
  62.         soapRequestData.append("<" + methodName + "ln>");  
  63.   
  64.         Set<String> nameSet = patameterMap.keySet();  
  65.         for (String name : nameSet) {  
  66.             soapRequestData.append("<" + name + ">" + patameterMap.get(name)  
  67.                     + "</" + name + ">");  
  68.         }  
  69.           
  70.         soapRequestData.append("</" + methodName + "ln>");  
  71.         soapRequestData.append("</" + methodName + ">");  
  72.         soapRequestData.append("</soapenv:Body>");  
  73.         soapRequestData.append("</soapenv:Envelope>");  
  74.         logger.info("soapRequestData:"+soapRequestData.toString());  
  75.         return soapRequestData.toString();  
  76.     }  
  77.       
  78.     public String getSoapResponseData() {  
  79.         return soapResponseData;  
  80.     }  
  81.           
  82.     /** 
  83.      * 获取文件的xml对象,然后获取对应的根节点root 
  84.      */  
  85.     public static void getRoot(String xmlString) throws Exception {  
  86.         Document document = DocumentHelper.parseText(xmlString);  
  87.         final Element root = document.getRootElement();// 获取根节点  
  88.         getNodes(root);// 从根节点开始遍历所有节点  
  89.     }  
  90.   
  91.     /** 
  92.      * 从指定节点Element node开始,递归遍历其所有子节点 
  93.      */  
  94.     @SuppressWarnings("unchecked")  
  95.     public static void getNodes(final Element node) {  
  96.         System.out.println("-------开始新节点-------------");  
  97.         // 当前节点的名称、文本内容和属性  
  98.         System.out.println("当前节点名称:" + node.getName());// 当前节点名称  
  99.         System.out.println("当前节点的内容:" + node.getTextTrim());// 当前节点内容  
  100.         final List<Attribute> listAttr = node.attributes();// 当前节点的所有属性  
  101.         for (final Attribute attr : listAttr) {// 遍历当前节点的所有属性  
  102.             final String name = attr.getName();// 属性名称  
  103.             final String value = attr.getValue();// 属性的值  
  104.             System.out.println("属性名称:" + name + "---->属性值:" + value);  
  105.         }  
  106.         // 递归遍历当前节点所有的子节点  
  107.         final List<Element> listElement = node.elements();// 所有一级子节点的list  
  108.         for (final Element e : listElement) {// 遍历所有一级子节点  
  109.             getNodes(e);// 递归  
  110.         }  
  111.     }  
  112.       
  113.     @SuppressWarnings("unchecked")  
  114.     public List<Map<String,String>> loadAdPlayListMap(){  
  115.         try {  
  116.              if (StringUtils.isNotBlank(adType) && adType.equals("13")) {  
  117.                 File adXmlFile = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + "lzw.xml");  
  118.                 String adXml = FileUtils.readFileToString(adXmlFile, IHttpRequest.DEFAULT_CHARSET);  
  119.                 Document document = DocumentHelper.parseText(adXml);  
  120.                 Element element = document.getRootElement();  
  121.                 List<Map<String, String>> list = new ArrayList<Map<String, String>>();  
  122.                 if (element != null) {  
  123.                     List<Element> itemElements = element.elements("item");  
  124.                     for (Element item : itemElements) {  
  125.                         List<Element> playerUrlElements = item.elements("playerUrl");  
  126.                         for (Element playerUrlElement : playerUrlElements) {  
  127.                             Map<String, String> map = new HashMap<String, String>();  
  128.                             map.put("type", playerUrlElement.attributeValue("type"));  
  129.                             map.put("duration", playerUrlElement.attributeValue("duration"));  
  130.                             map.put("name", playerUrlElement.attributeValue("name"));  
  131.                             String tag = playerUrlElement.attributeValue("tag");  
  132.                             map.put("tag", tag);  
  133.                             map.put("playerUrl", playerUrlElement.getTextTrim() + "&" + tag);  
  134.                             list.add(map);  
  135.                         }  
  136.                     }  
  137.                     this.adPlayListMap = list;  
  138.                     logger.debug("xml信息:{}",JsonUtils.objectToJson(this.adPlayListMap));  
  139.                     return adPlayListMap;  
  140.                 }  
  141.             }  
  142.         } catch (IOException e) {  
  143.             e.printStackTrace();  
  144.         } catch (Exception e) {  
  145.             e.printStackTrace();  
  146.         }  
  147.         return null;  
  148.     }  
  149.       
  150.     public void parseXml() throws Exception {  
  151.         String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"  
  152.                     + "<voole>"  
  153.                         + "<list>"  
  154.                             + "<epg>"  
  155.                                 + "<title>hljgd</title>"  
  156.                                 + "<price>48.88</price>"  
  157.                             + "</epg>"  
  158.                             + "<epg>"  
  159.                                 + "<title mac=\"30026\">jndx</title>"  
  160.                                 + "<price>39.95</price>"  
  161.                             + "</epg>"  
  162.                         + "</list>"  
  163.                     + "</voole>";  
  164.         Document doc = DocumentHelper.parseText(xml);  
  165.         Element database = (Element) doc.selectSingleNode("/voole/list/epg[2]");  
  166.         @SuppressWarnings("unchecked")  
  167.         List<Element> list = database.elements(); // 得到database元素下的子元素集合  
  168.         for (Element element : list) {  
  169.             // getName()是元素名,getText()是元素值  
  170.             System.out.println(element.getName() + ": " + element.getText());  
  171.         }  
  172.         List<?> fieldList = doc.selectNodes("//*[name()='title']");  
  173.         Iterator<?> fieldItr = fieldList.iterator();  
  174.         while (fieldItr.hasNext()) {  
  175.             Element fieldElement = (Element) fieldItr.next();  
  176.             System.out.println("当前 XPath: " + fieldElement.getPath());  
  177.             String fieldName = fieldElement.getText(); // field  
  178.             System.out.println(fieldName); // name  
  179.             String fieldClass = fieldElement.attributeValue("mac"); // field  
  180.             System.out.println(fieldClass);  
  181.         }  
  182.     }  
  183.       
  184.     public static void main(String[] args) throws Exception {  
  185.         DynamicSoapclientCall dynamicHttpclientCall = new DynamicSoapclientCall(  
  186.                 "http://webservice.lzw.shtel.com""ServiceAuth",  
  187.                 "http://1.1.1.1/LzwAuth");  
  188.   
  189.         Map<String, String> patameterMap = new HashMap<String, String>();  
  190.   
  191.         patameterMap.put("SPID""1");  
  192.         patameterMap.put("UserID""12");  
  193.         patameterMap.put("UserToken""123");  
  194.         patameterMap.put("ProductID""1234");  
  195.         patameterMap.put("ServiceID""12345");  
  196.         patameterMap.put("ContentID""123456");  
  197.         patameterMap.put("TimeStamp""1234567");  
  198.         patameterMap.put("IP""12345678");  
  199.         patameterMap.put("MAC""123456789");  
  200.         patameterMap.put("TransactionID""1234567890");  
  201.   
  202.         String soapRequestData = dynamicHttpclientCall.buildRequestData(patameterMap);  
  203.         System.out.println(soapRequestData);  
  204.   
  205.         int statusCode = dynamicHttpclientCall.invoke(patameterMap);  
  206.         if(statusCode == 200) {  
  207.             logger.info("调用成功!");  
  208.             System.out.println(dynamicHttpclientCall.soapResponseData);  
  209.         } else {  
  210.             logger.info("调用失败!错误码:" + statusCode);  
  211.         }  
  212.     }