使用http调用webservice-wsdl服务

 工作对接需要,对webservice了解不深,知道wsdl地址,就下载了Soap UI工具。大家自行下载,网上比较多。

Soap UI工具使用起来也简单,直接把wsdl地址粘贴进去,就知道有什么方法了,就可以测试了。

这里简单说下使用方法:

       直接点file,然后new soap project,然后在弹出填入wsdl地址,点击ok,然后左侧,就会有目录树生成,选里面的方法,点击request,按enter,就出现右侧request框,有参数填参数,没参数,直接点运行,最右侧就生成response了。大致可以看下图:

       熟悉了Soap UI工具,对wsdl有了一点点了解,输入,输出都是xml格式,但是在项目中,大部分使用json格式的,所以,我自己写了一个通用一点的方法,在结果返回那里,可能获取的层级不对,我是按我的来写,如果大家使用的话,断点调试一下就可以了。

        getWsdl方法:实现原理就是前端传soap中缺少的参数进来(虽然是json输入,但是实际参数里面是xml),到后端拼接请求,这种写法在实际应用中可能不太实用,对前端造成困扰,但是,特殊定制,这种就比较通用,不会担心,因为某一个参数不同,导致请求失败

       getWebService方法:这种就是标准json格式,使用起来,有些服务总数请求失败,因为我的特殊定制,所有没有用这个

      总体来说,要熟悉wsdl,就先下个soap UI工具,请求一下,看了请求和返回,你就了解他的格式了

package com.zhuzhu.common.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.impl.llom.util.AXIOMUtil;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.client.Stub;
import org.apache.axis.constants.Style;
import org.apache.axis.constants.Use;
import org.apache.axis.description.OperationDesc;
import org.apache.axis.description.ParameterDesc;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import javax.xml.namespace.QName;
import java.io.IOException;
import java.rmi.RemoteException;
import java.util.*;

/**
 * @ClassName: WebServiceUtils
 * @Description: webService工具类
 * @author: zhuzhu
 * @date: 2020/06/08
 */
public class WebServiceUtils extends Stub {
    public static void main(String[] args) throws RemoteException {
        JSONObject json = new JSONObject();
        json.put("url", "http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx?wsdl");
        json.put("method", "getMobileCodeInfo");
        json.put("targetNamespace", "http://WebXml.com.cn/");
        json.put("mobileCode", "13419672002");
        String result = getWebService(json);
        System.out.println(result);
    }
//    public static void main(String[] args) throws RemoteException {
//        JSONObject json = new JSONObject();
//        json.put("url", "http://www.webxml.com.cn/webservices/qqOnlineWebService.asmx?wsdl");
//        json.put("targetNamespace", "xmlns:web=\"http://WebXml.com.cn/\"");
//        List<String> list = new ArrayList<>();
//        list.add("<web:qqCheckOnline>");
//        list.add("<web:qqCode>369543107</web:qqCode>");
//        list.add("</web:qqCheckOnline>");
//        json.put("body", list);
//        String result = getWsdl(json);
//        System.out.println(result);
//    }

    /**
     * @param json
     * @return
     * @Description: 请求wsdl服务
     * @Title: getWsdl
     */
    public static String getWsdl(JSONObject json) {
        try {
            String wsdlURL = json.getString("url");
            String targetNamespace = json.getString("targetNamespace");
            JSONArray body = json.getJSONArray("body");
            // 设置编码。(因为是直接传的xml,所以我们设置为text/xml;charset=utf8)
            final String contentType = "text/xml;charset=utf8";
            /// 拼接要传递的xml数据(注意:此xml数据的模板我们根据wsdlURL从SoapUI中获得,只需要修改对应的变量值即可)
            StringBuffer xMLcontent = new StringBuffer("");
            xMLcontent.append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\"");
            xMLcontent.append(" " + targetNamespace + ">\n");
            xMLcontent.append("   <soapenv:Header/>\n");
            xMLcontent.append("   <soapenv:Body>\n");
            for (int i = 0; i < body.size(); i++) {
                xMLcontent.append("   " + body.getString(i) + "\n");
            }
            xMLcontent.append("   </soapenv:Body>\n");
            xMLcontent.append("</soapenv:Envelope>");
            // 调用工具类方法发送http请求
            String responseXML = doHttpPostByHttpClient(wsdlURL, contentType, xMLcontent.toString());
            // 将xml数据转换为OMElement
            OMElement omElement = AXIOMUtil.stringToOM(responseXML);
            // 根据responseXML的数据样式,定位到对应element,然后获得其childElements,遍历
            Iterator<OMElement> it = omElement.getFirstElement().getFirstElement().getChildElements();
            while (it.hasNext()) {
                OMElement element = it.next();
                if (StringTool.equalsIgnoreCase(element.getLocalName(), "return")) {
                    return element.getText();
                }
            }
            return "";
        } catch (Exception e) {
            System.out.println("error ------" + e.toString());
            return "";
        }
    }

    /**
     * 使用apache的HttpClient发送http
     *
     * @param wsdlURL     请求URL
     * @param contentType 如:application/json;charset=utf8
     * @param content     数据内容
     * @DATE 2018年9月22日 下午10:29:17
     */
    private static String doHttpPostByHttpClient(final String wsdlURL, final String contentType, final String content) throws ClientProtocolException, IOException {
        // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        // 创建Post请求
        HttpPost httpPost = new HttpPost(wsdlURL);
        StringEntity entity = new StringEntity(content.toString(), "UTF-8");
        // 将数据放入entity中
        httpPost.setEntity(entity);
        httpPost.setHeader("Content-Type", contentType);
        // 响应模型
        CloseableHttpResponse response = null;
        String result = null;
        try {
            // 由客户端执行(发送)Post请求
            response = httpClient.execute(httpPost);
            // 从响应模型中获取响应实体
            // 注意:和doHttpPostByRestTemplate方法用的不是同一个HttpEntity
            org.apache.http.HttpEntity responseEntity = response.getEntity();
            System.out.println("响应ContentType为:" + responseEntity.getContentType());
            System.out.println("响应状态为:" + response.getStatusLine());
            if (responseEntity != null) {
                result = EntityUtils.toString(responseEntity);
                System.out.println("响应内容为:" + result);
            }
        } finally {
            // 释放资源
            if (httpClient != null) {
                httpClient.close();
            }
            if (response != null) {
                response.close();
            }
        }
        return result;
    }

    /**
     * @param json
     * @return
     * @Description: 发送webservice服务
     * @Title: getWebService
     */
    public static String getWebService(JSONObject json) {
        try {
            Service service = new Service();
            Call call = (Call) service.createCall();
            //WSDL地址的targetNamespace和接口名称
            call.setSOAPActionURI(json.getString("targetNamespace") + json.getString("method"));
            //WSDL地址带?wsdl
            call.setTargetEndpointAddress(json.getString("url"));
            //WSDL里面描述的接口名称
            call.setOperationName(json.getString("method"));
            json.remove("url");
            json.remove("targetNamespace");
            //参数构建
            call.setOperation(initOperationDesc1(json));
            //处理输入参数
            Iterator iter = json.entrySet().iterator();
            List<String> list = new ArrayList<>();
            while (iter.hasNext()) {
                Map.Entry entry = (Map.Entry) iter.next();
                list.add(entry.getValue().toString());
            }
            String[] arrString = list.toArray(new String[list.size()]);
            Object[] obj = arrString;
            String result = (String) call.invoke(obj);
            System.out.println("result is ------" + result);
            return result;
        } catch (Exception e) {
            System.out.println("error ------" + e.toString());
            return "";
        }
    }

    /**
     * @param json
     * @return
     * @Description:组合参数
     * @Title: initOperationDesc1
     */
    private static OperationDesc initOperationDesc1(JSONObject json) {
        OperationDesc oper = new OperationDesc();
        Set<String> it = json.keySet();
        oper.setName(json.getString("method"));
        json.remove("method");
        for (String key : it) {
            ParameterDesc param = new ParameterDesc(new QName("", key), ParameterDesc.IN, new QName("http://www.w3.org/2001/XMLSchema", "string"), String.class, false, false);
            param.setOmittable(true);
            oper.addParameter(param);
        }
        oper.setReturnType(new QName("http://www.w3.org/2001/XMLSchema", "string"));
        oper.setReturnClass(String.class);
        oper.setReturnQName(new QName("", "return"));
        oper.setStyle(Style.WRAPPED);
        oper.setUse(Use.LITERAL);
        return oper;
    }
}

 

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
使用WSDL本地客户端调用Web服务的步骤如下: 1. 获取WSDL文件。WSDL文件包含了Web服务的定义信息,可以通过Web浏览器访问Web服务的URL,并在URL后面添加“?wsdl”参数,从而获取WSDL文件。 2. 使用WSDL2Java工具生成客户端代码。WSDL2Java是一个Java开发工具,可以将WSDL文件转换为Java客户端代码。你可以从Apache CXF或Apache Axis等Web服务框架中找到WSDL2Java工具。 以Apache CXF为例,在命令行中输入以下命令生成客户端代码: ``` wsdl2java -p <package-name> -d <output-directory> <wsdl-url> ``` 其中,`<package-name>`是客户端代码的Java包名,`<output-directory>`是客户端代码的输出目录,`<wsdl-url>`是Web服务WSDL文件URL。 3. 编写客户端代码。在生成的客户端代码中,可以找到代表Web服务Java接口。你需要实例化该接口,并调用接口中定义的方法来调用Web服务。 ``` // 实例化Web服务接口 ServiceName serviceName = new ServiceName(); WebServicePortType port = serviceName.getWebServicePort(); // 调用Web服务方法 String result = port.webServiceMethod(param1, param2, ...); ``` 其中,`ServiceName`是生成的代表Web服务Java类,`WebServicePortType`是Web服务接口,`webServiceMethod`是Web服务中定义的方法。 4. 运行客户端代码。你可以将客户端代码打包成一个可执行的Java应用程序,并在命令行中运行该应用程序,从而调用Web服务。 以上是使用WSDL本地客户端调用Web服务的基本步骤。需要注意的是,不同的Web服务框架和工具可能会有所不同,具体步骤请参考相关的文档或教程。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值