Java调用WebServices接口

当拿到一个WebServices接口时,首先用接口测试工具调用一下接口,看是否可以正常发送请求和获取返回接口,确保接口是没有问题的,可以用SoapUI工具进行测试。

下面以一个免费的天气预报接口为例,记录整个接口的调用过程。

接口地址:http://ws.webxml.com.cn/WebServices/WeatherWS.asmx

打开SoapUI,点击SOAP,在弹出的新建页面输入接口地址,在地址后面拼接上 ?wsdl ,点击OK。

会看到在左侧地方显示该接口可以调用的每个方法。

获取上海的天气信息:

点击绿色剪箭头,就可以在右侧看到接口的返回结果。

以上就是用SoapUI工具进行接口测试的使用说明。

下面用Java代码来实现该接口的调用:

新建一个测试类 WebServiceTest

java 复制代码
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;

/**
 * @author: liangmeng
 * @description: WebService测试
 * @date: 2024/4/14 13:42
 * @version: 1.0
 */
public class WebServiceTest {
    public static void main(String[] args) {
        String soapRequestXml = null;
        String soapResponseXml = null;
        String responseCode = null;
        HashMap<String, String> responseData = new HashMap<>();


        //soap报文
        soapRequestXml = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:web=\"http://WebXml.com.cn/\">\n" +
                "   <soapenv:Header/>\n" +
                "   <soapenv:Body>\n" +
                "      <web:getWeather>\n" +
                "         <web:theCityCode>上海</web:theCityCode>\n" +
                "         <web:theUserID>5fc88ce5ff404ce6ba1282125f68d258</web:theUserID>\n" +
                "      </web:getWeather>\n" +
                "   </soapenv:Body>\n" +
                "</soapenv:Envelope>";

        //发送post请求
        responseData = postSoap("http://ws.webxml.com.cn/WebServices/WeatherWS.asmx", soapRequestXml, "http://WebXml.com.cn/getWeather");
        responseCode = responseData.get("responseCode");
        soapResponseXml = responseData.get("responseMsg");
        System.out.println("请求状态:"+responseCode);
        System.out.println("返回参数:"+soapResponseXml);

    }


    /**
     * @param postUrl: 请求地址
     * @param soapXml: 请求报文
     * @param soapAction: 请求方法名称
     * @return HashMap<String,String>
     * @author 梁萌
     * @description 发送POST请求
     * @date 2024/4/14 13:49
     */
    public static HashMap<String, String> postSoap(String postUrl, String soapXml, String soapAction) {

        HashMap<String, String> hm = new HashMap<>();

        //响应结果
        StringBuilder result = new StringBuilder();
        //输出流
        OutputStream out = null;
        //字符缓冲输入流
        BufferedReader in = null;
        //状态响应码
        int responseCode = 0;

        try {
            //创建URL
            URL url = new URL(postUrl);//重要,WSDL路径,不带?wsdl
            URLConnection connection = url.openConnection();
            HttpURLConnection httpConn = (HttpURLConnection) connection;

            //设置参数
            httpConn.setRequestProperty("Content-Length", String.valueOf(soapXml.getBytes(StandardCharsets.UTF_8).length));
            httpConn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
            httpConn.setRequestProperty("SOAPAction", soapAction); //重要,调用接口的某个方法
            httpConn.setRequestMethod("POST");
            httpConn.setDoOutput(true);
            httpConn.setDoInput(true);

            //发送请求
            out = httpConn.getOutputStream();
            out.write(soapXml.getBytes(StandardCharsets.UTF_8));

            //状态响应码
            responseCode = httpConn.getResponseCode();

            //状态响应码=200
            in = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), StandardCharsets.UTF_8));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                result.append(inputLine);
            }
        } catch (Exception ex) {
            System.out.println("soap请求路径:" + postUrl + ",异常,响应状态码:" + responseCode + ",异常原因:" + ex.getMessage());
            hm.put("responseCode", responseCode + "");
            hm.put("responseMsg", ex.getMessage() + "");
            return hm;
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (Exception ex) {
                System.out.println("soap请求路径:" + postUrl + ",异常,响应状态码:" + responseCode + ",异常原因:释放资源失败");
                hm.put("responseCode", responseCode + "");
                hm.put("responseMsg", ex.getMessage() + "");
                return hm;
            }
        }

        //返回响应内容
        String soapResponse = result.toString();
        System.out.println("soap请求路径:" + postUrl + ",结束,响应状态码:" + responseCode + ",返回结果:" + soapResponse);

        hm.put("responseCode", responseCode + "");
        hm.put("responseMsg", soapResponse + "");
        return hm;
    }


}

执行结果:

成功通过Java程序获取到了接口的返回信息。

代码中有几个需要注意的地方:

1.请求地址中不需要添加 ?wsdl

2.请求的方法名称(postSoap方法的第三个参数soapAction),需要与SoapUI工具中的soapAction参数值保持一致,参见下图的内容:

相关推荐
夜月行者2 分钟前
如何使用ssm实现基于SSM的宠物服务平台的设计与实现+vue
java·后端·ssm
程序猿小D6 分钟前
第二百六十七节 JPA教程 - JPA查询AND条件示例
java·开发语言·前端·数据库·windows·python·jpa
潘多编程20 分钟前
Java中的状态机实现:使用Spring State Machine管理复杂状态流转
java·开发语言·spring
_阿伟_39 分钟前
SpringMVC
java·spring
代码在改了1 小时前
springboot厨房达人美食分享平台(源码+文档+调试+答疑)
java·spring boot
wclass-zhengge1 小时前
数据结构篇(绪论)
java·数据结构·算法
何事驚慌1 小时前
2024/10/5 数据结构打卡
java·数据结构·算法
结衣结衣.1 小时前
C++ 类和对象的初步介绍
java·开发语言·数据结构·c++·笔记·学习·算法
TJKFYY1 小时前
Java.数据结构.HashSet
java·开发语言·数据结构
kylinxjd1 小时前
spring boot发送邮件
java·spring boot·后端·发送email邮件