zoukankan      html  css  js  c++  java
  • WebService

    demo:https://www.cnblogs.com/fengwenzhee/p/6915606.html

    4种客户端实现方式:http://blog.csdn.net/csdn_gia/article/details/54863549

    soapUI工具:webservice服务端配置好,可通过soapUI工具模拟发送soap消息体,各种测试,总之很方便的一工具

    soapUtils工具类:通过HttpConnection来访问webservice服务(soap1.1,soap1.2),其中还有工具的使用方式

    package tools.perkinelmer.utls;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.nio.charset.StandardCharsets;
    
    /**
     * soap工具
     * @author wangj01052
     *
     */
    public class SoapUtil {
        /**
         * 
         * @param endpoint
         * @param action 有值soap1.1;无值soap1.2协议
         * @param soapXml soap1.1;soap1.2 文本不一样注意改变
         * @return
         * @throws IOException
         */
        public static String invokeSrvSoap1(String endpoint,String action, String soapXml) throws IOException{  
            String result ="";
            //第一步:创建服务地址,不是WSDL地址  
                    URL url = new URL("http://www.webxml.com.cn/WebServices/IpAddressSearchWebService.asmx");  
                    //第二步:打开一个通向服务地址的连接  
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();  
                    //第三步:设置参数  
                    //3.1发送方式设置:POST必须大写  
                    connection.setRequestMethod("POST");  
                    if(action==null||"".equals(action)){//soap1.2协议
                        //3.2设置数据格式:content-type  
                        connection.setRequestProperty("Content-Type", "application/soap+xml; charset=utf-8"); 
                    }else{//soap1.1协议
                        //3.2设置数据格式:content-type  
                        connection.setRequestProperty("Content-Type", "text/xml;charset=utf-8"); 
                        connection.setRequestProperty("SOAPAction", action);
                    }
                    
                    //3.3设置输入输出,因为默认新创建的connection没有读写权限,  
                    connection.setDoInput(true);  
                    connection.setDoOutput(true);  
              
                    //第四步:组织SOAP数据,发送请求  
                    OutputStream os = connection.getOutputStream();  
                    os.write(soapXml.getBytes(StandardCharsets.UTF_8));  
                    //第五步:接收服务端响应,打印  
                    int responseCode = connection.getResponseCode();  
                    if(200 == responseCode){//表示服务端响应成功  
                        InputStream is = connection.getInputStream();  
                        InputStreamReader isr = new InputStreamReader(is);  
                        BufferedReader br = new BufferedReader(isr);  
                          
                        StringBuilder sb = new StringBuilder();  
                        String temp = null;  
                        while(null != (temp = br.readLine())){  
                            sb.append(temp);  
                        }  
                        result = sb.toString();
                        is.close();  
                        isr.close();  
                        br.close();  
                    }  
              
                    os.close(); 
            
            return result;
        }  
        
        //工具调用方式类似,这里不能直接用
        public static void main(String[] args) throws Exception {  
            //soap1.1协议
            String soapXML1  = "<?xml version="1.0" ?><S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/"><S:Body><getCountryCityByIp xmlns="http://WebXml.com.cn/"><theIpAddress>127.0.0.1</theIpAddress></getCountryCityByIp></S:Body></S:Envelope>";
            String endPoint1 = "http://www.webxml.com.cn/WebServices/IpAddressSearchWebService.asmx";
            String soapAction1 ="http://WebXml.com.cn/getCountryCityByIp";
            System.out.println(invokeSrvSoap1(endPoint1, soapAction1, soapXML1));
            //soap1.2协议
            String soapXML2 = "<?xml version="1.0" encoding="utf-8"?><soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope"><soap12:Body><getCountryCityByIp xmlns="http://WebXml.com.cn/"><theIpAddress>127.0.0.1</theIpAddress></getCountryCityByIp></soap12:Body></soap12:Envelope>";
            String endPoint2 = "http://www.webxml.com.cn/WebServices/IpAddressSearchWebService.asmx";
            System.out.println(invokeSrvSoap1(endPoint2,null, soapXML2));
            
        }
    }
    View Code

    客户端改变目标地址:

        String endpointURL = "http://127.0.0.1:8181/WS_Server/WebService";
        BindingProvider bp = (BindingProvider)wsImpl;
        bp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, endpointURL);
    package client;
    
    import javax.xml.ws.BindingProvider;
    
    import tools.perkinelmer.service.serviceimpl.WebServiceImpl;
    import tools.perkinelmer.service.serviceimpl.WebServiceImplService;
    
    /**
     * webservice调用服务的方式一:通过java工具Wsimport
     * 该种方式使用简单,但一些关键的元素在代码生成时写死到生成代码中,不方便维护,所以仅用于测试。
     * @author wangj01052
     *
     */
    public class WSClient {
        public static void main(String[] args){
            WebServiceImplService factory = new WebServiceImplService();
            WebServiceImpl wsImpl =factory.getWebServiceImplPort();
            
            //4.1改变目标地址
            String endpointURL = "http://127.0.0.1:8181/WS_Server/WebService";
            BindingProvider bp = (BindingProvider)wsImpl;
            bp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, endpointURL);
            String resResult =wsImpl.sayHello("xiaoping");
            System.out.println("调用WebService的sayHello方法返回结果:"+resResult);
        }
    }
    View Code

    可能会遇到的问题:

      1)springboot+mybatis+webservice 依赖注入@Autowired不起作用

        在项目config文件下新建两个文件,WebApplicationContextLocator.java,SpringBootBeanAutowiringSupport.java

    package tools.perkinelmer.config;
    
    import org.apache.ibatis.logging.Log;
    import org.apache.ibatis.logging.LogFactory;
    import org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor;
    import org.springframework.util.Assert;
    import org.springframework.util.ClassUtils;
    import org.springframework.web.context.WebApplicationContext;
    
    public abstract class SpringBootBeanAutowiringSupport {
    
        private static final Log logger = LogFactory.getLog(SpringBootBeanAutowiringSupport.class);
    
    
        /**
         * This constructor performs injection on this instance,
         * based on the current web application context.
         * <p>Intended for use as a base class.
         * @see #processInjectionBasedOnCurrentContext
         */
        public SpringBootBeanAutowiringSupport() {
            System.out.println("SpringBootBeanAutowiringSupport.SpringBootBeanAutowiringSupport");
            processInjectionBasedOnCurrentContext(this);
        }
    
    
        /**
         * Process {@code @Autowired} injection for the given target object,
         * based on the current web application context.
         * <p>Intended for use as a delegate.
         * @param target the target object to process
         * @see org.springframework.web.context.ContextLoader#getCurrentWebApplicationContext()
         */
        public static void processInjectionBasedOnCurrentContext(Object target) {
            Assert.notNull(target, "Target object must not be null");
            WebApplicationContext cc = WebApplicationContextLocator.getCurrentWebApplicationContext();
            if (cc != null) {
                AutowiredAnnotationBeanPostProcessor bpp = new AutowiredAnnotationBeanPostProcessor();
                bpp.setBeanFactory(cc.getAutowireCapableBeanFactory());
                bpp.processInjection(target);
            }
            else {
                if (logger.isDebugEnabled()) {
                    logger.debug("Current WebApplicationContext is not available for processing of " +
                            ClassUtils.getShortName(target.getClass()) + ": " +
                            "Make sure this class gets constructed in a Spring web application. Proceeding without injection.");
                }
            }
        }
    }
    View Code
    package tools.perkinelmer.config;
    import javax.servlet.ServletContext;
    import javax.servlet.ServletException;
    
    import org.springframework.boot.web.servlet.ServletContextInitializer;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.context.WebApplicationContext;
    import org.springframework.web.context.support.WebApplicationContextUtils;
    
    @Configuration
    public class WebApplicationContextLocator  implements ServletContextInitializer {
    
        private static WebApplicationContext webApplicationContext;
    
        public static WebApplicationContext getCurrentWebApplicationContext() {
            return webApplicationContext;
        }
    
        /**
         * 在启动时将servletContext 获取出来,后面再读取二次使用。
         * @param servletContext
         * @throws ServletException
         */
        @Override
        public void onStartup(ServletContext servletContext) throws ServletException {
            webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
        }
    }
    View Code

        之后在websevice实现类上继承SpringBootBeanAutowiringSupport即可,可参考

    package tools.perkinelmer.service.serviceImpl;
    
    import java.util.List;
    import java.util.Map;
    import javax.jws.WebService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import tools.perkinelmer.config.SpringBootBeanAutowiringSupport;
    import tools.perkinelmer.mapper.CommMapper;
    import tools.perkinelmer.service.IPKISignalWS;
    
    @WebService
    @Service
    public class PKISignalWSImpl extends SpringBootBeanAutowiringSupport implements IPKISignalWS {
     
        @Autowired(required=true)
        private CommMapper commMapper;
    
        @Override
        public String getPatientNameByBLH(String BLH) {
            String sql = "exec usp_GetPatientNameByBLH @BLH = '"+BLH+"'";
            List<Map<String,Object>> result= commMapper.commSelectSql(sql);
            return result.get(0).toString();
        }
    }
    View Code

        这样操作后就能@Autowired就能生效了

    参考:https://www.jianshu.com/p/125258ada53b

    1.介绍

      webservice主要解决两个系统两个应用程序间的远程调用,它提供了webapi方式访问,跨语言跨平台

    2.原理

      webservice的客户端与服务端进行交互的时候使用xml来传递数据,

      soap协议,即简单对象访问协议,它是webservice的客户端与服务端进行交互的时候遵守的一个协议

    3.方式

      通过jdk自带工具wsimport,根据服务说明书生成本地java代码,之后通过这个本地代码访问webservice

      wsimport -s . -p webservice http://127.0.0.1:8080/helloService?wsdl

      webservice:java文件下载到本地的文件夹位置(相对cmd命令位置)

      /helloService:提供调用的类文件名 

    4.例子

      1)服务端

        1.1  IMyServer

    package test;
    
    import javax.jws.WebService;
    
    @WebService
    public interface IMyServer {
         public int add(int a,int b);
         public int minus(int a,int b);
    }

        1.2 MyServerImpl 实现类

    package test;
    
    import javax.jws.WebService;
    
    @WebService(endpointInterface="test.IMyServer")
    public class MyServerImpl implements IMyServer{
    
        @Override
        public int add(int a, int b) {
            System.out.println(a+"+"+b+"="+(a+b));
            return a+b;
        }
    
        @Override
        public int minus(int a, int b) {
            System.out.println(a+"-"+b+"="+(a-b));
            return a-b;
        }
    
    }

      3.主程序发布代码

    package test;
    
    import javax.xml.ws.Endpoint;
    
    public class test {
        public static void main(String[] args){
            String address = "http://localhost:9999/ns";
            Endpoint.publish(address, new MyServerImpl());
        }
    }

      2)客户端

        先使用wximport方式下载分享类及其关联类,在将java文件都复制到新客户端项目中

        调用

    import testwebservice.IMyServer;
    import testwebservice.MyServerImplService;
    
    public class application {
        public static void main(String[] args){
            IMyServer myserver =new MyServerImplService().getMyServerImplPort();
            Integer result = myserver.add(2, 2);
            System.out.println(result);
        }
    }

      5. 网络上很多wsdl资源可以获取别人资源

      http://www.webxml.com.cn/zh_cn/web_services.aspx

      获得手机归属地webservce:

      wsimport -s . -p lenve.test.phone http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx?wsdl

  • 相关阅读:
    如何保持页脚始终在页面底部
    CSS自适应宽度圆角按钮
    ACM1004
    java输出格式
    北大ACM1001题Exponentiation(求高精度幂)
    深入理解sizeof
    java之类BigDecimal
    ACM1003
    ACM1005
    C的输出格式printf
  • 原文地址:https://www.cnblogs.com/xiaoping1993/p/webservice.html
Copyright © 2011-2022 走看看