GVKun编程网logo

客户端xmlhttp调用webservice(webservice接口调用 xml参数组装)

8

在本文中,我们将给您介绍关于客户端xmlhttp调用webservice的详细内容,并且为您解答webservice接口调用xml参数组装的相关问题,此外,我们还将为您提供关于axis调用webser

在本文中,我们将给您介绍关于客户端xmlhttp调用webservice的详细内容,并且为您解答webservice接口调用 xml参数组装的相关问题,此外,我们还将为您提供关于axis 调用webservice (客户端)、C#客户端通过安全凭证调用webservice、CXF客户端开发--动态调用webservice、CXF客户端调用https Webservice的知识。

本文目录一览:

客户端xmlhttp调用webservice(webservice接口调用 xml参数组装)

客户端xmlhttp调用webservice(webservice接口调用 xml参数组装)

Truly
2005-08-17

 

  • 下载本文的源码(C#) - 25k
  • 下载本文的源码(VB) - 25k

     

    摘要

    很多时候大家需要使用xmlhttp来实现无刷新的从服务器获取数据,本文以实例代码来介绍本在客户端对WebService的调用

    主要分为3种类型

  • 通过SOAP对WebService进行调用
  • 通过HTTP POST对WebService进行调用
  • 借助MS的webservice.htc简化调用

    注:本文代码均以C#代码作为基础,对于使用VB代码的需要注意WebService的命名空间,详细请看下载链接中源码

    SOAP对WebService进行调用

    <SCRIPT language="JavaScript">
                            // Client invoke WebService use SOAP request and response
                            function GetHelloWorld_SOAP(i)
                            {
                            var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
                            var soapMessage,soapData,URL;
                            // Set the soap message
                            soapMessage = "<?xml version=/"1.0/" encoding=/"utf-8/"?>";
                            soapMessage += "<soap:Envelope xmlns:xsi=/"http://www.w3.org/2001/XMLSchema-instance/""
                            + " xmlns:xsd=/"http://www.w3.org/2001/XMLSchema/" xmlns:soap=/"http://schemas.xmlsoap.org/soap/envelope//">";
                            soapMessage += "<soap:Body>";
                            // Set the data for soap body ---- begin ------
                            soapData = "<HelloWorld xmlns=/"http://tempuri.org//">";
                            soapData += "    <i>" + i + "</i>";
                            soapData += "</HelloWorld>";
                            // Set the data for soap body ----  end  ------
                            soapMessage = soapMessage + soapData + "</soap:Body>";
                            soapMessage = soapMessage + "</soap:Envelope>";
                            URL = "Service1.asmx"; //可以使用相对地址或完整URL
                            xmlhttp.Open("POST",URL,false);
                            xmlhttp.SetRequestHeader ("Content-Type","text/xml; charset=utf-8");
                            xmlhttp.SetRequestHeader ("SOAPAction","http://tempuri.org/HelloWorld");
                            xmlhttp.send(soapMessage);
                            alert(soapMessage)
                            var x =   xmlhttp.responseXML;
                            alert(x.childNodes[1].text);
                            //那么如何知道是否调用成功呢,状态为200说明调用成功,500则说明出错
                            alert(xmlhttp.Status);
                            alert(xmlhttp.StatusText);
                            }
                            </SCRIPT>
                            
    <SCRIPT language="vbscript">
                            '' Client invoke WebService use SOAP request and response
                            Function vbGetHelloWorld_SOAP(i)
                            dim soapMessage,URL
                            '' Set the soap message
                            soapMessage = "<?XML version=""1.0"" encoding=""utf-8""?>"
                            soapMessage = soapMessage & "<SOAP:ENVELOPE xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"""
                            +" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"">"
                            soapMessage = soapMessage & "<SOAP:BODY>"
                            '' Set the data for soap body ---- begin ------
                            soapData = "<HELLOWORLD xmlns=""http://tempuri.org/"">"
                            soapData = soapData & "    <I>" & i & "</I>"
                            soapData = soapData & "</HELLOWORLD>"
                            '' Set the data for soap body ----  end  ------
                            soapMessage = soapMessage & soapData & "</SOAP:BODY>"
                            soapMessage = soapMessage & "</SOAP:ENVELOPE>"
                            URL = "Service1.asmx" ''可以使用相对地址或完整URL
                            Set xmlhttp = CreateObject("Microsoft.XMLHTTP")
                            xmlhttp.Open "POST",False
                            xmlhttp.SetRequestHeader "Content-Type","text/xml; charset=utf-8"
                            xmlhttp.SetRequestHeader "SOAPAction","http://tempuri.org/HelloWorld"
                            xmlhttp.send(soapMessage)
                            Set x2 =   xmlhttp.responseXML
                            alert(x2.childNodes(1).text)
                            ''那么如何知道是否调用成功呢,状态为200说明调用成功,500则说明出错
                            alert(xmlhttp.Status)
                            alert(xmlhttp.StatusText)
                            End Function
                            </SCRIPT>
                            
    JavaScript vbscript
     

    通过HTTP POST对WebService进行调用

    <SCRIPT language="JavaScript">
                            // Client invoke WebService use HTTP POST request and response
                            function GetHelloWorld_HTTPPOST(i)
                            {
                            var URL = "http://localhost/WSInvoke/Service1.asmx/HelloWorld";
                            var Params = "i=" + i;// Set postback parameters
                            var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
                            xmlhttp.Open("POST","application/x-www-form-urlencoded");
                            xmlhttp.SetRequestHeader ("Content-Length",Params.length);
                            xmlhttp.send(Params);
                            var x =   xmlhttp.responseXML;
                            alert(x.childNodes[1].text);
                            //那么如何知道是否调用成功呢,状态为200说明调用成功,500则说明出错
                            alert(xmlhttp.Status);
                            alert(xmlhttp.StatusText);
                            }
                            </SCRIPT>
                            
    <SCRIPT language="vbscript">
                            '' Client invoke WebService use HTTP POST request and response
                            Function vbGetHelloWorld_HTTPPOST(i)
                            URL = "http://localhost/WSInvoke/Service1.asmx/HelloWorld"
                            Params = "i=" & i '' Set postback parameters
                            Set xmlhttp = CreateObject("Microsoft.XMLHTTP")
                            xmlhttp.Open "POST",False
                            xmlhttp.setRequestHeader "Content-Type","application/x-www-form-urlencoded"
                            xmlhttp.setRequestHeader "Content-Length",LEN(Params)
                            xmlhttp.Send(Params)
                            Set x =   xmlhttp.responseXML
                            alert(x.childNodes(1).text)
                            ''那么如何知道是否调用成功呢,状态为200说明调用成功,500则说明出错
                            alert(xmlhttp.Status)
                            alert(xmlhttp.StatusText)
                            Set xmlhttp = nothing
                            End Function
                            </SCRIPT>
                            
    JavaScript vbscript
     

    借助MS的webservice.htc简化调用

    webservice.htc是MS提供的一个对webservie常用方法的封装,可以从ms官方网站下载,安装iewebcontrols时也会安装到你的网站根目录下,使用时需要注意路径。请注意代码中body的属性设置,更多对WebService.htc的介绍,点击这里。

     

    <SCRIPT language="JavaScript">
                            function Init()
                            {
                            // establishes a friendly name for a Web service URL
                            wsCaller.useService("http://localhost/WSInvoke/Service1.asmx?WSDL","HW");
                            }
                            function callWS(i)
                            {
                            wsCaller.HW.callService(Handler_HW,"HelloWorld",i);
                            }
                            function Handler_HW(result)
                            {
                            // if there is an error,and the call came from the call() in init()
                            if(result.error)
                            {
                            // Pull the error information from the event.result.errorDetail properties
                            var xfaultcode   = result.errorDetail.code;
                            var xfaultstring = result.errorDetail.string;
                            var xfaultsoap   = result.errorDetail.raw;
                            // Add code to handle specific error codes here
                            }
                            // if there was no error
                            else
                            {
                            document.all.Text1.value = result.value;
                            }
                            }
                            </SCRIPT>
                            <BODY id="wsCaller" onload="Init()">
                            <INPUT type="text" id="Text1" name="Text1">
                            <INPUT onclick="callWS(1)" type="button" value="Invoke" id="Button1" name="Button1">
                            
     

     

     

    Web Service 的完整代码(C#,Service1.asmx.cs)

    using System;
                            using System.Collections;
                            using System.ComponentModel;
                            using System.Data;
                            using System.Diagnostics;
                            using System.Web;
                            using System.Web.Services;
                            namespace WSInvoke
                            {
                            /// <SUMMARY>
                            /// Summary description for Service1.
                            /// </SUMMARY>
                            public class Service1 : System.Web.Services.WebService
                            {
                            public Service1()
                            {
                            //CODEGEN: This call is required by the ASP.NET Web Services Designer
                            InitializeComponent();
                            }
                            #region Component Designer generated code
                            //required by the Web Services Designer
                            private IContainer components = null;
                            /// <SUMMARY>
                            /// required method for Designer support - do not modify
                            /// the contents of this method with the code editor.
                            /// </SUMMARY>
                            private void InitializeComponent()
                            {
                            }
                            /// <SUMMARY>
                            /// Clean up any resources being used.
                            /// </SUMMARY>
                            protected override void dispose( bool disposing )
                            {
                            if(disposing && components != null)
                            {
                            components.dispose();
                            }
                            base.dispose(disposing);
                            }
                            #endregion
                            // WEB SERVICE EXAMPLE
                            // The HelloWorld() example service returns the string Hello World
                            // To build,uncomment the following lines then save and build the project
                            // To test this web service,press F5
                            [WebMethod]
                            public string HelloWorld(int i)
                            {
                            return "Hello World" + i;
                            }
                            }
                            }
                            
     

     

    测试所用的html页面(Invoke.html)

    <HTML>
                            <BODY>
                            <INPUT type="button" value="SOAP" onclick="GetHelloWorld_SOAP(''1'')" id="Button1" name="Button1">
                            <INPUT type="button" value="HTTPPOST" onclick="GetHelloWorld_HTTPPOST(''2'')" id="Button2" name="Button2">
                            <INPUT type="button" value="异常测试" onclick="GetHelloWorld_SOAP('''')" id="Button3" name="Button3"><BR><BR>
                            <INPUT type="button" value="vbSOAP" onclick="vbGetHelloWorld_SOAP(''3'')" id="Button4" name="Button4">
                            <INPUT type="button" value="vbHTTPPOST" onclick="vbGetHelloWorld_HTTPPOST(''4'')" id="Button5" name="Button5">
                            </BODY>
                            </HTML>
                            
     
    很晚了,先把代码贴上。有空的时候把异步操作再仔细分析一下 :B

     

    附表1(IXMLHTTPRequest - 属性)

    Name Type Description
    onreadystatechange N/A 指定当就绪状态发生改变时调用的事件处理函数,仅用于异步操作
    readyState Long 异步操作的状态:未初始化(0),正在加载(1),已加载(2),交互(3),已完成(4)
    responseBody Variant 将响应信息正文作为unsigned byte数组返回
    responseStream Variant 将响应信息正文作为一个ADO Stream对象返回
    responseText String 将响应信息正文作为一个文本字符串返回
    responseXML Object 通过XMLDom将响应信息正文解析为XMLDocument对象
    status Long 服务器返回的HTTP状态码
    statusText String 服务器HTTP响应行状态

    附表2(IXMLHTTPRequest - 方法)

    Name Desciption
    abort 取消当前 HTTP 请求
    getAllResponseHeaders 从响应信息中检索所有的标头字段
    getResponseHeader 从响应信息正文中获得一个 HTTP 标头值
    open(method,url,boolAsync,bstrUser,bstrPassword) 打开一个与 HTTP 服务器的连接
    send(varBody) 设定一个请求的标头字段
    setRequestHeader(bstrHeader,bstrValue) 向 HTTP 服务器发送请求。可包含正文。
  •  来自: http://truly.cnblogs.com/archive/2005/08/18/218102.html

    axis 调用webservice (客户端)

    axis 调用webservice (客户端)

    package com.client;

    import javax.xml.namespace.QName;

    import org.apache.axis.client.Call;
    import org.apache.axis.client.Service;

    public class AxisClient {
     public static void main(String[] args) {
      try {
       String endpoint = "
    http://localhost:8080/ServiceTest/services/Math?wsdl";

       Service service = new Service();
       Call call = (Call) service.createCall();

       call.setTargetEndpointAddress(new java.net.URL(endpoint));
       call.setoperationName(new QName("
    http://demo.webservice.samland/","echo"));

       String ret = (String) call.invoke(new Object[] {"Samland"});

       System.out.println("Sent ''Hello!'',got ''" + ret + "''");
      } catch (Exception e) {
       System.err.println(e.toString());
      }
     }

    C#客户端通过安全凭证调用webservice

    C#客户端通过安全凭证调用webservice

    怎么解决给XML Web services 客户端加上安全凭据,从而实现调用安全的远程web方法?
    首先,有远程web服务Service继承自System.Web.Services.Protocols.soapHttpClientProtocol。

    再者,步骤有三:
    1,建立凭据NetworkCredential。
    2,设置凭据Service.Credentials。
    3,设置预身份验证,这样在已经建立的连接上再次调用方法时就会把凭据加上。代码如下

                    NetworkCredential credential = new System.Net.NetworkCredential("username","passw0rd");//凭据
                    CredentialCache credentialCache = new CredentialCache();//为多个凭据提供存储
                    credentialCache.Add(new Uri(Service.Url),"Basic",credential);
                    Service.Credentials = credentialCache;//获取或设置 XML Web services 客户端身份验证的安全凭据
                    Service.PreAuthenticate = true;//预身份验证

     

    最后,客户端调用web方法Service.WebMethod()。

    发现的问题是web方法被调用了很多次才生效。通过网络抓包工具,发现每次向远程服务器发起post请求时http头没有加上凭据Authentication: basic 密文。解决办法是通过在Service内部重写GetWebRequest方法,在调用基类方法得到的WebRequest上添加一个head为Authentication: basic 密文,从而实现每次发送post请求是加上凭据。缺点是密文被写死,也不是自动生成的。

    CXF客户端开发--动态调用webservice

    CXF客户端开发--动态调用webservice

    之前关于webservice的文章中已经介绍了CXF JAX-WS proxy客户端模式。JAX-WS proxy模式需要在客户端使用wsdl2java生成代理接口,这种方式相对于动态调用,其效率相对较高。但是前期的工作量比较大,有时我们知道一个服务接口URL、方法名、入参schema、返回参数schema,不想和jax-ws proxy模式那么繁琐的生成客户端代码,就需要使用动态调用。

    动态调用的方式很简单,代码一般很简洁。需要使用一个动态客户端工厂类:JaxWsDynamicclientFactory,并有它创建某个接口的客户端。如下:

    public class Dynamicclient {

    private final static String SERVICE_URL = "http://localhost:8080/services/xxtInter?wsdl";

    public static void main(String[] args) throws Exeception{

    JaxWsDynamicclientFactory FACTORY = JaxWsDynamicclientFactory.newInstance();//1,获取一个工厂实例

    Client client = FACTORY.createClient(serviceURL);//2,生成针对指定服务接口URL的客户端

    Object[] objs = client.invoke("sayHi","Hello World!");//3,调用指定的方法,注意入参第一个为方法名称,第二个为方法的参数(可以传入一个参数列表,一般为数组)
    System.out.print(objs[0].toString());

    }

    }

    到此,完成CXF客户端动态调用的流程。看看代码是不是很简单,明了。

    不过在调用方法的步骤,需要注意,方法参数(针对复杂类型,如pojo,list等)的schema必须和服务端的一样。

    关于动态调用传递复杂类型参数,将在后面文章中进行介绍。

    CXF客户端调用https Webservice

    CXF客户端调用https Webservice

    @H_301_4@ 1.生成服务器端所需证书文件

    #设置变量
    set OPENSSL_CONF=openssl.cfg
    # 生成一个RSA密钥 
    openssl genrsa -des3 -out server.key 1024
    # 生成一个证书请求
    openssl req -new -key server.key -out server.csr
    # 拷贝一个不需要输入密码的密钥文件
    openssl rsa -in server.key -out server_nopwd.key
    # 自己签发证书
    openssl x509 -req -days 3650 -in server.csr -signkey server.key -out server.crt
    @H_301_4@

    @H_301_4@

    @H_301_4@ 2.生成cxf调用https webservice 所用的证书文件

    #从key和crt生成pkcs12格式的keystore
    openssl pkcs12 -export -in server.crt -inkey server.key -out server.p12 -name tomcat -CAfile server.crt -caname root -chain
    #生成需要的keystore
    keytool -importkeystore -v -srckeystore mycert.p12 -srcstoretype pkcs12 -srcstorepass 123456 -destkeystore tomcat.keystore -deststoretype jks -deststorepass 123456
    @H_301_4@

    @H_301_4@

    @H_301_4@ 3.客户端代码

    package cn.net.sunge.gdms.util;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.security.KeyStore;
    import java.util.Map;
    
    import javax.net.ssl.KeyManager;
    import javax.net.ssl.KeyManagerFactory;
    import javax.net.ssl.TrustManager;
    import javax.net.ssl.TrustManagerFactory;
    
    import org.apache.cxf.configuration.jsse.TLSClientParameters;
    import org.apache.cxf.endpoint.Client;
    import org.apache.cxf.frontend.ClientProxy;
    import org.apache.cxf.jaxws.JaxWsProxyfactorybean;
    import org.apache.cxf.transport.http.HTTPConduit;
    
    public class WsClientUtil {
    
    	public static <T> T getInterface(Class<T> clazz,String address) {
    		return getInterface(clazz,address,null);
    	}
    
    	@SuppressWarnings("unchecked")
    	public static <T> T getInterface(Class<T> clazz,String address,Map<String,Object> properties) {
    		JaxWsProxyfactorybean factory = new JaxWsProxyfactorybean();
    		factory.setAddress(address);
    		factory.setServiceClass(clazz);
    		if (null != properties) {
    			factory.setProperties(properties);
    		}
    		return (T) factory.create();
    	}
    
    	public static <T> T getHttpsInterface(Class<T> clazz,String jksPath,String jksPwd) {
    		return getHttpsInterface(clazz,jksPath,jksPwd,null);
    	}
    
    	@SuppressWarnings("unchecked")
    	public static <T> T getHttpsInterface(Class<T> clazz,String jksPwd,Object> properties) {
    		JaxWsProxyfactorybean factory = new JaxWsProxyfactorybean();
    		factory.setAddress(address);
    		factory.setServiceClass(clazz);
    		if (null != properties) {
    			factory.setProperties(properties);
    		}
    		T t = (T) factory.create();
    		configureSSLOnTheClient(t,jksPwd);
    		return t;
    	}
    
    	private static void configureSSLOnTheClient(Object obj,String jksPwd) {
    		File file = new File(jksPath);
    
    		Client client = ClientProxy.getClient(obj);
    		HTTPConduit httpConduit = (HTTPConduit) client.getConduit();
    
    		try {
    			TLSClientParameters tlsParams = new TLSClientParameters();
    			tlsParams.setdisableCNCheck(true);
    
    			KeyStore keyStore = KeyStore.getInstance("JKS");
    			String password = jksPwd;
    			String storePassword = jksPwd;
    
    			keyStore.load(new FileInputStream(file),storePassword.tochararray());
    			TrustManagerFactory trustFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    			trustFactory.init(keyStore);
    			TrustManager[] trustManagers = trustFactory.getTrustManagers();
    			tlsParams.setTrustManagers(trustManagers);
    
    			keyStore.load(new FileInputStream(file),storePassword.tochararray());
    			KeyManagerFactory keyFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    			keyFactory.init(keyStore,password.tochararray());
    			KeyManager[] keyManagers = keyFactory.getKeyManagers();
    			tlsParams.setKeyManagers(keyManagers);
    
    			// FiltersType filtersTypes = new FiltersType();
    			// filtersTypes.getInclude().add(".*_EXPORT_.*");
    			// filtersTypes.getInclude().add(".*_EXPORT1024_.*");
    			// filtersTypes.getInclude().add(".*_WITH_DES_.*");
    			// filtersTypes.getInclude().add(".*_WITH_NULL_.*");
    			// filtersTypes.getExclude().add(".*_DH_anon_.*");
    			// tlsParams.setCipherSuitesFilter(filtersTypes);
    
    			tlsParams.setdisableCNCheck(true);
    
    			httpConduit.setTlsClientParameters(tlsParams);
    		} catch (Exception e) {
    			e.printstacktrace();
    		}
    	}
    }
    @H_301_4@ 参考资料:

    @H_301_4@ http://bbs.csdn.net/topics/350150090
    http://www.educity.cn/wenda/130283.html
    http://www.voidcn.com/article/p-tmywelna-nt.html
    http://bbs.csdn.net/topics/350150090
    http://aruld.info/programming-ssl-for-jetty-based-cxf-services/
    http://www.voidcn.com/article/p-gwravcec-ke.html
    http://zhidao.baidu.com/link?url=YCxDHHSJWpuin3OdnmN9QUj7lauIEAHi2RE6BT0cwk22G3eqbX30Dr-OXcJt0hYCHZcp27e3iAx0xIG8IyInOqzq2YUCDbON78D3rOJ1y_7

    今天关于客户端xmlhttp调用webservicewebservice接口调用 xml参数组装的介绍到此结束,谢谢您的阅读,有关axis 调用webservice (客户端)、C#客户端通过安全凭证调用webservice、CXF客户端开发--动态调用webservice、CXF客户端调用https Webservice等更多相关知识的信息可以在本站进行查询。

    本文标签: