zoukankan      html  css  js  c++  java
  • WebService客户端几种实现方式

    1、jdk原生调用(需要获取服务接口文件)

    import java.net.URL;
    
    import javax.xml.namespace.QName;
    import javax.xml.ws.Service;
    
    import com.soft.platform.webservice.server.MyService;
    
    public class WsClient {
    
    	public static void main(String[] args) throws Exception {
    		URL url = new URL("http://192.168.0.101:8089/myservice?wsdl");
    		// 指定命名空间和服务名称
    		QName qName = new QName("http://com.soft.ws/my", "MyService");
    		Service service = Service.create(url, qName);
    		// 通过getPort方法返回指定接口
    		MyService myServer = service.getPort(new QName("http://com.soft.ws/my",
    				"LoginPort"), MyService.class);
    		// 调用方法 获取返回值
    		String result = myServer.authorization("admin", "123456");
    		System.out.println(result);
    	}
    
    }
    返回结果: success
    

    2.import生成客户端代码
    wsimport -d d:/webservice -keep -p com.soft.test.wsimportClient -verbose http://192.168.0.101:8089/myservice?wsdl
    这里写图片描述

    public static void main(String[] args) {
    		MyService_Service service = new MyService_Service();
    		MyService login = service.getLoginPort();
    		String result = login.authorization("admin", "123456");
    		System.out.println(result);
    	}
    

    3、cxf两种调用方式。

    public static void main(String[] args) {
    		JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
    		factory.setServiceClass(MyService.class);
    		factory.setAddress("http://192.168.0.101:8089/myservice?wsdl");
    		// 需要服务接口文件
    		MyService client = (MyService) factory.create();
    		String result = client.authorization("admin", "123456");
    		System.out.println(result);
    	}
    

      

    public static void main(String[] args) throws Exception {
    		//采用动态工厂方式 不需要指定服务接口
    		JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
    		Client client = dcf
    				.createClient("http://192.168.0.101:8089/myservice?wsdl");
    		QName qName = new QName("http://com.soft.ws/my", "authorization");
    		Object[] result = client.invoke(qName,
    				new Object[] { "admin", "123456" });
    		System.out.println(result[0]);
    	}
    

    4、axis调用方式

    import java.net.MalformedURLException;
    import java.net.URL;
    import java.rmi.RemoteException;
    
    import javax.xml.namespace.QName;
    import javax.xml.rpc.ParameterMode;
    import javax.xml.rpc.ServiceException;
    
    import org.apache.axis.client.Call;
    import org.apache.axis.client.Service;
    import org.apache.axis.encoding.XMLType;
    
    public class WsAClient {
         /**
    	 * 跨平台调用Web Service出现
    	 *  faultString: 服务器未能识别 HTTP 头 SOAPAction 的值: 
    	 * JAX-WS规范不需要SoapAction,但是.NET需要,所以产生了这个错误。 
    	 * options.setAction("目标的TargetNameSpace"+"调用的方法名");
    	 */
    	public static void main(String[] args) {
    		String url = "http://192.168.0.101:8089/myservice?wsdl";
    		Service service = new Service();
    		try {
    			Call call = (Call) service.createCall();
    			call.setTargetEndpointAddress(new URL(url));
    			// WSDL里面描述的接口名称(要调用的方法)
    			call.setOperationName(new QName("http://com.soft.ws/my",
    					"authorization"));
    			//跨平台调用加上这个
    		   call.setUseSOAPAction(true);
    		   call.setSOAPActionURI("http://com.soft.ws/my/authorization");
    			// 接口方法的参数名, 参数类型,参数模式 IN(输入), OUT(输出) or INOUT(输入输出)
    			call.addParameter("userId", XMLType.XSD_STRING, ParameterMode.IN);
    			call.addParameter("password", XMLType.XSD_STRING, ParameterMode.IN);
    			// 设置被调用方法的返回值类型
    			call.setReturnType(XMLType.XSD_STRING);
    			// 设置方法中参数的值
    			Object result = call.invoke(new Object[] { "admin", "123456" });
    
    			System.out.println(result.toString());
    		} catch (ServiceException | RemoteException | MalformedURLException e) {
    			e.printStackTrace();
    		}
    	}
    
    }
    

    axis方式依赖的相关jar包如下:
    在这里插入图片描述

    5、httpClient调用方式。

    (1)maven依赖如下

    <properties>
    <httpclient.version>4.5.6</httpclient.version>
    </properties>
    
    <dependencies>
    <dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>${httpclient.version}</version>
    </dependency>
    </dependencies>
    

    (2)httpclient作为客户端调用webservice。代码如下

    /*
     * Copyright (c)
     */
    package test;
    
    import org.apache.http.client.config.RequestConfig;
    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.HttpClients;
    import org.apache.http.util.EntityUtils;
    
    import java.nio.charset.Charset;
    
    /**
     * webservice客户端
     *
     * @author David Lin
     * @version: 1.0
     * @date 2018-09-09 12:16
     */
    public class SoapClient {
    
        public static void main(String args[]) throws Exception {
            //soap服务地址
            String url = "http://localhost:8888/ssm/Services/UserService?wsdl";
            StringBuilder soapBuilder = new StringBuilder(64);
            soapBuilder.append("<?xml version="1.0" encoding="UTF-8"?>");
            soapBuilder.append("<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:web="http://webservice.soft.com/">");
            soapBuilder.append("   <soapenv:Header/>");
            soapBuilder.append("       <soapenv:Body>");
            soapBuilder.append("             <web:authorization>");
            soapBuilder.append("                     <userId>").append("admin").append("</userId>");
            soapBuilder.append("                     <password>").append("123456").append("</password>");
            soapBuilder.append("               </web:authorization>");
            soapBuilder.append("    </soapenv:Body>");
            soapBuilder.append("</soapenv:Envelope>");
    
            //创建httpcleint对象
            CloseableHttpClient httpClient = HttpClients.createDefault();
            //创建http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 构建请求配置信息
            RequestConfig config = RequestConfig.custom().setConnectTimeout(1000) // 创建连接的最长时间
                    .setConnectionRequestTimeout(500) // 从连接池中获取到连接的最长时间
                    .setSocketTimeout(3 * 1000) // 数据传输的最长时间10s
                    .build();
            httpPost.setConfig(config);
            CloseableHttpResponse response = null;
            try {
                //采用SOAP1.1调用服务端,这种方式能调用服务端为soap1.1和soap1.2的服务
                httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8");
    
                //采用SOAP1.2调用服务端,这种方式只能调用服务端为soap1.2的服务
                // httpPost.setHeader("Content-Type", "application/soap+xml;charset=UTF-8");
                StringEntity stringEntity = new StringEntity(soapBuilder.toString(), Charset.forName("UTF-8"));
                httpPost.setEntity(stringEntity);
                response = httpClient.execute(httpPost);
                // 判断返回状态是否为200
                if (response.getStatusLine().getStatusCode() == 200) {
                    String content = EntityUtils.toString(response.getEntity(), "UTF-8");
                    System.out.println(content);
    
                } else {
                    System.out.println("调用失败!");
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (null != response) {
                    response.close();
                }
                if (null != httpClient) {
                    httpClient.close();
                }
            }
    
    
        }
    }
    

    返回结果为:

    <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
    <soap:Body>
    <ns2:authorizationResponse xmlns:ns2="http://webservice.soft.com/">
    <return>success</return>
    </ns2:authorizationResponse>
    </soap:Body>
    </soap:Envelope>
    

    (3)用Jsoup提取响应数据。
    maven依赖

    <properties>
          <jsoup.version>1.11.3</jsoup.version>
      </properties>
      
      <dependencies>
      
        <dependency>
          <groupId>org.jsoup</groupId>
          <artifactId>jsoup</artifactId>
          <version>${jsoup.version}</version>
        </dependency>
        
      </dependencies>
    

    代码如下:

     Document soapRes = Jsoup.parse(content);
     Elements returnEle = soapRes.getElementsByTag("return");
    
     System.out.println("调用结果为:"+returnEle.text());
    
  • 相关阅读:
    NOI 2020 游记
    BJOI2020 游记
    行列式
    CSP-S 2019 游记
    类欧几里得算法
    有关二次离线和 Yuno loves sqrt technology II
    NOI2019 游记
    CTS 2019 Pearl
    BJOI2019 游记
    2017 山东二轮集训 Day7 国王
  • 原文地址:https://www.cnblogs.com/mracale/p/10578686.html
Copyright © 2011-2022 走看看