Java调用WebServices接口

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

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

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

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

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

获取上海的天气信息:

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

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

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

新建一个测试类 WebServiceTest

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
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值