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参数值保持一致,参见下图的内容:

相关推荐
_星辰大海乀几秒前
表的设计、聚合函数
java·数据结构·数据库·sql·mysql·数据库开发
IT成长史9 分钟前
deepseek梳理java高级开发工程师微服务面试题-进阶版
java·spring cloud·微服务
zkmall19 分钟前
Java + 鸿蒙双引擎:ZKmall开源商城如何定义下一代B2C商城技术标准?
java·开源·harmonyos
陌路物是人非20 分钟前
uniapp取消浏览自动填充
java·服务器·uni-app
獨枭22 分钟前
使用 163 邮箱实现 Spring Boot 邮箱验证码登录
java·spring boot·后端
伍六星22 分钟前
maven和npm区别是什么
java·npm·maven
才知山高路远26 分钟前
Java - Junit框架
java·junit·log4j
维基框架27 分钟前
Spring Boot 封装 MinIO 工具
java·spring boot·后端
秋野酱27 分钟前
基于javaweb的SpringBoot酒店管理系统设计与实现(源码+文档+部署讲解)
java·spring boot·后端
关于不上作者榜就原神启动那件事28 分钟前
Java基础学习
java·开发语言·学习