如何使用http请求来调用webService接口?
最近一直在调用webService服务接口,其中使用的工具一直是axis2,但是我感觉太麻烦了,在了解完webService请求后我发现其实这玩意就是个post请求加上了soap协议,然后我就自己封装了一个小工具,自己用着还是蛮方便的,感觉功能上还能满足我的日常工作,嘿嘿今天分享出来欢迎大家使用,有什么封装的不好或者不对的地方欢迎大家指正
在使用的过程中可能需要配合soapUi来使用,其实我个人在调用对方webService服务的时候都会去使用soapUi去测试一遍所以并没有感觉到有什么不方便的地方。
可配置项
-
配置调用超时时间:WebServiceHttpConnect connect=new WebServiceHttpConnect(超时时长);
[!IMPORTANT]
注:超时时长单位为毫秒,默认不传为10000ms
-
配置请求头:connect.addRequestHeader(“head1”,“xxx”);
[!IMPORTANT]
注:soap1.2的请求方式默认不带SOAPAction请求头,若有需要可自定义SOAPAction
connect.addRequestHeader(“SOAPAction”,“xxxxxxxx”);
调用方法说明
1.调用soap1.1接口
[!NOTE]
如何查找方法的SOAPAction?
打开wsdl文件找到你想要调用的方法名例如:
- 普通调用非https加密的调用: soap11HttpSend(String urlStr,String soapXml,String SOAPAction)
- https请求跳过ssl认证: soap11HttpsSend(String urlStr,String soapXml,String SOAPAction)
2.调用soap1.2接口
- 普通调用非https加密的调用: soap12HttpSend(String urlStr,String soapXml,String SOAPAction)
- https请求跳过ssl认证: soap12HttpsSend(String urlStr,String soapXml,String SOAPAction)
3.WebServiceUtils方法:截取指定标签内的内容
String body = WebServiceUtils.cutOutXml("标签名", "需要截取的xml");
使用流程
- 步骤一:将依赖拉取到自己的pom文件中maven地址为Maven Central: io.gitee.zhang-yiya:webservice-utils:3.0.0 (sonatype.com)
<dependency>
<groupId>io.gitee.zhang-yiya</groupId>
<artifactId>webservice-utils</artifactId>
<version>3.0.0</version>
</dependency>
- 步骤二:创建一个WebServiceHttpConnect对象
WebServiceHttpConnect connect=new WebServiceHttpConnect();
//或5000为请求超时时间单位为ms,默认不填为10000ms
WebServiceHttpConnect connect=new WebServiceHttpConnect(5000);
- 步骤三:向服务端发送请求
ResponseExample responseExample = connect.soap12HttpSend("请求地址", "包含soap协议的xml");
需要注意的是这个地方的请求内容是包含soap协议的请求内容,我个人配合着soapUi来使用的,因为我在调用第三方服务的时候也会用这个工具去测一下对方的接口通不通,地址就是对方提供webService的服务。例如截图如下(soapUi举例)
- 步骤四:获取状态码和响应内容
Integer responseCode = responseExample.getResponseCode(); //状态码
String responseContext = responseExample.getResponseContext(); //相应内容
调用示例
WebServiceHttpConnect connect=new WebServiceHttpConnect();
String url="http://www.webxml.com.cn/WebServices/WeatherWebService.asmx";
String soapXml="<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:web=\"http://WebXml.com.cn/\">\n" +
" <soap:Header/>\n" +
" <soap:Body>\n" +
" <web:getSupportProvince/>\n" +
" </soap:Body>\n" +
"</soap:Envelope>";
ResponseExample responseExample = connect.soap12HttpSend(url, soapXml); //请求
Integer responseCode = responseExample.getResponseCode(); //状态码
String responseContext = responseExample.getResponseContext(); //相应内容