https+xml服务端/客户端java后台编写及soapUI https测试

前端之家收集整理的这篇文章主要介绍了https+xml服务端/客户端java后台编写及soapUI https测试前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

一、https+xml服务端编写

1.1 创建证书文件

1.1.1 创建服务器KeyStore

[plain] view plain copy
  1. keytool-genkey-aliasserver_jks_cennavi-keyalgRSA-keypass123456-storepass123456-keystoreserver.jks-validity3650

1.1.2 导出服务端证书

1.1.3 创建客户端KeyStore

1.1.4 导出客户端Cer证书

[html] copy
    keytool-export-trustcacerts-aliasclient_p12_cennavi-fileclient.cer-keystoreclient.p12-storepass123456-storetypePKCS12

1.1.5 交换证书

1.3.1 编写servlet服务端代码

编写servlet代码,用于获取用户https+xml/http+xml请求,解析请求后进行相应业务为逻辑处理返回相应信息给请求方。
[java] copy
    packagecom.hsinghsu.test.web.servlet;
  1. importjava.io.ByteArrayOutputStream;
  2. importjava.io.IOException;
  3. importjava.io.InputStream;
  4. importjava.util.HashMap;
  5. importjava.util.Iterator;
  6. importjava.util.Map;
  7. importjava.util.zip.GZIPOutputStream;
  8. importjavax.servlet.ServletException;
  9. importjavax.servlet.ServletRequest;
  10. importjavax.servlet.ServletResponse;
  11. importjavax.servlet.http.HttpServlet;
  12. importjavax.servlet.http.HttpServletRequest;
  13. importjavax.servlet.http.HttpServletResponse;
  14. importorg.dom4j.Attribute;
  15. importorg.dom4j.Document;
  16. importorg.dom4j.Element;
  17. importorg.dom4j.io.SAXReader;
  18. publicclassTestInterfaceServletextendsHttpServlet
  19. {
  20. /**
  21. *对外接口主入口
  22. *用于获取用户请求,返回用户请求使用。
  23. */
  24. publicvoidservice(ServletRequestrequest,ServletResponseresponse)
  25. throwsServletException,IOException
  26. HttpServletResponsehttpResponse=(HttpServletResponse)response;
  27. HttpServletRequesthttprequest=(HttpServletRequest)request;
  28. httpResponse.setContentType("text/html;charset=UTF-8");
  29. Map<String,String>mapHeader=getHeaderMap(httprequest);//获取http头信息
  30. StringrequestXml="";//请求过来的xml报文
  31. StringresponseXml="";//返回的xml报文
  32. Documentdoc=null;
  33. InputStreamis=request.getInputStream();
  34. System.out.println("======httpheadertimestampis:"+mapHeader.get("timestamp"));
  35. SAXReadersaxReader=newSAXReader();
  36. newHashMap<String,String>();
  37. try
  38. doc=saxReader.read(is);
  39. requestXml=doc.asXML();
  40. System.out.println("======requestxml:"+requestXml);
  41. ElementrootElm=doc.getRootElement();//从root根节点获取请求报文
  42. map=parseXML(rootElm,newHashMap<String,String>());
  43. Stringmsgname=map.get("msgname");//从httpbody中获取到的msgname值
  44. //是否https访问
  45. if(request.isSecure())
  46. {
  47. //https访问
  48. if("loginReq".equals(msgname))
  49. System.out.println("thehttps+xmlrequestisloginReq");
  50. responseXml=
  51. "<?xmlversion=\"1.0\"encoding=\"UTF-8\"?><ecity><msgname>loginRep</msgname><msgversion>1.0.0</msgversion><result><rspcode>0</rspcode><rspdesc>成功</rspdesc></result><svccont><uid>111</uid></svccont></ecity>";
  52. }
  53. else
  54. System.out.println("请求接口名称不在本系统内");
  55. "<?xmlversion=\"1.0\"encoding=\"UTF-8\"?><ecity><msgversion>1.0.0</msgversion><result><rspcode>1</rspcode><rspdesc>请求接口名称不在本系统内</rspdesc></result></ecity>";
  56. }
  57. else
  58. //http访问
  59. if("logoutReq".equals(msgname))
  60. System.out.println("thehttp+xmlrequestislogout");
  61. "<?xmlversion=\"1.0\"encoding=\"UTF-8\"?><ecity><msgname>logoutRep</msgname><msgversion>1.0.0</msgversion><result><rspcode>0</rspcode><rspdesc>成功</rspdesc></result><svccont><uid>111</uid></svccont></ecity>";
  62. catch(Exceptione1)
  63. System.out.println("请求数据不正确");
  64. responseXml=
  65. "<?xmlversion=\"1.0\"encoding=\"UTF-8\"?><ecity><msgversion>1.0.0</msgversion><result><rspcode>2</rspcode><rspdesc>请求数据不正确</rspdesc></result></ecity>";
  66. //对报文进行压缩处理
  67. StringAcceptEncoding="gzip";
  68. if(mapHeader!=null)
  69. AcceptEncoding=mapHeader.get("Accept-Encoding");
  70. if(null!=AcceptEncoding&&"gzip".equals(AcceptEncoding))
  71. //使用gzip压缩报文
  72. System.out.println("======outputresponsexmlwithgzipis:"+responseXml);
  73. response.getOutputStream().write(gZip(responseXml.getBytes()));
  74. response.getOutputStream().flush();
  75. response.getOutputStream().close();
  76. //不压缩报文,直接传输
  77. System.out.println("======outputresponsexmlwithoutgzipis:"+responseXml);
  78. response.getOutputStream().write(responseXml.getBytes());
  79. /**
  80. *获取http头信息
  81. *<功能详细描述>
  82. *@paramrequest
  83. *@return
  84. *@see[类、类#方法、类#成员]
  85. publicMap<String,String>getHeaderMap(HttpServletRequestrequest)
  86. Map<String,String>();
  87. if(null!=request.getHeader("msgname")&&!"".equals(request.getHeader("msgname")))
  88. map.put("msgname",request.getHeader("msgname"));
  89. if(null!=request.getHeader("Accept-Encoding")&&!"".equals(request.getHeader("Accept-Encoding")))
  90. map.put("Accept-Encoding",request.getHeader("Accept-Encoding"));
  91. if(null!=request.getHeader("timestamp")&&!"".equals("timestamp"))
  92. map.put("timestamp",request.getHeader("timestamp"));
  93. returnmap;
  94. *将xml解析成map键值对
  95. *<功能详细描述>
  96. *@paramele需要解析的xml对象
  97. *@parammap入参为空,用于内部迭代循环使用
  98. privateMap<String,String>parseXML(Elementele,Map<String,String>map)
  99. for(Iterator<?>i=ele.elementIterator();i.hasNext();)
  100. Elementnode=(Element)i.next();
  101. System.out.println("======parseXMLnodename:"+node.getName());
  102. if(node.attributes()!=null&&node.attributes().size()>0)
  103. for(Iterator<?>j=node.attributeIterator();j.hasNext();)
  104. Attributeitem=(Attribute)j.next();
  105. System.out.println("======parseXMLpropertyname:"+item.getName()+"propertyvalue:"
  106. +item.getValue()+"\n");
  107. map.put(item.getName(),item.getValue());
  108. if(node.getText().length()>0)
  109. System.out.println("======parseXMLnodevalue:"+node.getText());
  110. map.put(node.getName(),node.getText());
  111. if(node.elementIterator().hasNext())
  112. parseXML(node,map);
  113. returnmap;
  114. *gZip压缩方法
  115. *将原报文通过gzip压缩
  116. *@paramdata
  117. publicstaticbyte[]gZip(byte[]data)
  118. byte[]b=null;
  119. ByteArrayOutputStreambos=newByteArrayOutputStream();
  120. GZIPOutputStreamgzip=newGZIPOutputStream(bos);
  121. gzip.write(data);
  122. gzip.finish();
  123. gzip.close();
  124. b=bos.toByteArray();
  125. bos.close();
  126. catch(Exceptionex)
  127. ex.printStackTrace();
  128. returnb;
  129. }

1.3.2 web.xml配置

在web.xml中配置访问该接口的servlet,详见配置如下: 注:如果在servlet中需要注入service/dao的bean,请参见:http://www.it165.net/pro/html/201307/6589.html 【如何用Spring将Service注入到Servlet中(注解模式)】

1.3.3 启动服务端

启动服务端tomcat。服务端的访问地址为:https://127.0.0.1:8843/testhttps/interface

二、https+xml客户端编写

2.1 编写客户端java代码,示例如下:

copy
importjava.io.BufferedReader;
  • importjava.io.InputStreamReader;
  • importorg.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
  • importorg.apache.commons.httpclient.HttpClient;
  • importorg.apache.commons.httpclient.HttpStatus;
  • importorg.apache.commons.httpclient.methods.PostMethod;
  • importorg.apache.commons.httpclient.methods.StringRequestEntity;
  • importorg.apache.commons.httpclient.params.HttpMethodParams;
  • importorg.dom4j.Document;
  • publicclassTestReqServletextendsHttpServlet
  • publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)
  • //StringsURL="http://127.0.0.1:8080/testhttps/interface";
  • StringsURL="https://127.0.0.1:8443/testhttps/interface";
  • Stringxml=
  • "<?xmlversion='1.0'encoding='UTF-8'?><ecity><msgname>loginReq</msgname><timestamp>20140422094111</timestamp><svccont><token>112255</token></svccont></ecity>";
  • toHTTPS(sURL,xml);
  • *https调用
  • *@paramsURL请求URL
  • *@paramxml请求报文
  • *@return
  • *@throwsIOException
  • publicStringtoHTTPS(StringsURL,Stringxml)
  • throwsIOException
  • sURL="https://127.0.0.1:8443/testhttps/interface";
  • System.setProperty("javax.net.ssl.trustStore","C:\\Users\\hsinghsu\\Desktop\\https\\client.jks");
  • System.setProperty("javax.net.ssl.trustStorePassword","123456");
  • System.setProperty("javax.net.ssl.keyStoreType","PKCS12");
  • System.setProperty("javax.net.ssl.keyStore","C:\\Users\\hsinghsu\\Desktop\\https\\client.p12");
  • System.setProperty("javax.net.ssl.keyStorePassword","123456");
  • //注:去掉以上5行则表示使用http协议访问
  • StringresultXML="";
  • HttpClienthttpClient=null;
  • PostMethodpostMethod=null;
  • httpClient=newHttpClient();
  • //设置超时时间
  • httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(30000);
  • httpClient.getHttpConnectionManager().getParams().setSoTimeout(30000);
  • postMethod=newPostMethod(sURL);
  • postMethod.setRequestEntity(newStringRequestEntity(xml,"text/html","UTF-8"));
  • postMethod.setRequestHeader("Content-Type","text/xml;charset=UTF-8");
  • postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,newDefaultHttpMethodRetryHandler());
  • intstatusCode=httpClient.executeMethod(postMethod);
  • if(statusCode!=HttpStatus.SC_OK)
  • System.out.println("Callmethodfailed:"+postMethod.getStatusLine());
  • BufferedReaderin=null;
  • try
  • in=newBufferedReader(newInputStreamReader(postMethod.getResponseBodyAsStream(),"utf-8"));
  • SAXReadersaxReader=newSAXReader();
  • Documentdoc=saxReader.read(newInputStreamReader(postMethod.getResponseBodyAsStream(),255)"> resultXML=doc.asXML();
  • catch(IOExceptione)
  • e.printStackTrace();
  • finally
  • if(in!=null)
  • in.close();
  • catch(Exceptione)
  • if(postMethod!=null)
  • postMethod.releaseConnection();
  • returnresultXML;
  • }
  • 配置完成后使用servlet访问即可测试

    三、soapUI测试https+xml接口

    打开soapUI,File-->Preferences-->SSL Settings,导入client.p12,输入密码即可
    注:以上配置为https双向验证,若只要https服务端的单向验证,则去掉client.p12 SOAPUI配置证书即可。
    原文链接:/xml/295155.html

    猜你在找的XML相关文章