C# WebClient调用WebService

WebClient调用WebService

(文末下载完整代码)

先上代码:

      object[] inObjects = new[] { "14630, 14631" };
      HttpWebClient wc = new HttpWebClient(2300);
      var result1 = WebServiceClientHelper.InvokeWebService("ESBService_TEST", "http://localhost/ESBService/VitalSign.svc?wsdl", "QueryVocabSet", inObjects, wc);
      WriteLine(result1.ToString());
    public class HttpWebClient : WebClient
    {
        /// <summary>
        /// 初始化需要设置超时时间,以毫秒为单位
        /// </summary>
        /// <param name="timeout">毫秒为单位</param>
        public HttpWebClient(int timeout)
        {
            Timeout = timeout;
        }

        public int Timeout { get; set; }

        /// <summary>
        /// 重写 GetWebRequest,添加 WebRequest 对象超时时间
        /// </summary>
        protected override WebRequest GetWebRequest(Uri address)
        {
            HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(address);
            request.Timeout = Timeout;
            request.ReadWriteTimeout = Timeout;
            return request;
        }
    }

  HttpWebRequest 改造依据:

WebClient

HttpWebRequest

提供用于将数据发送到由 URI 标识的资源及从这样的资源接收数据的常用方法。

public class HttpWebRequest : WebRequest, ISerializable

Assembly location:

C:\Windows\Microsoft.NET\Framework\v4.0.30319\System.dll

Assembly location:

C:\Windows\Microsoft.NET\Framework\v4.0.30319\System.dll

    protected virtual WebRequest GetWebRequest(Uri address)
    {
      WebRequest request = WebRequest.Create(address);
      this.CopyHeadersTo(request);
      if (this.Credentials != null)
        request.Credentials = this.Credentials;
      if (this.m_Method != null) request.Method = this.m_Method; if (this.m_ContentLength != -1L) request.ContentLength = this.m_ContentLength; if (this.m_ProxySet) request.Proxy = this.m_Proxy; if (this.m_CachePolicy != null) request.CachePolicy = this.m_CachePolicy; return request; } protected virtual WebResponse GetWebResponse(WebRequest request) { WebResponse response = request.GetResponse(); this.m_WebResponse = response; return response; }

 

 

    public class HttpWebClient : WebClient
    {
        /// <summary>
        /// 初始化需要设置超时时间,以毫秒为单位
        /// </summary>
        /// <param name="timeout">毫秒为单位</param>
        public HttpWebClient(int timeout)
        {
            Timeout = timeout;
        }

        public int Timeout { get; set; }

        /// <summary>
        /// 重写 GetWebRequest,添加 WebRequest 对象超时时间
        /// </summary>
        protected override WebRequest GetWebRequest(Uri address)
        {
            HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(address); request.Timeout = Timeout; request.ReadWriteTimeout = Timeout; return request; } }

 

  调用服务处理:

        public static object InvokeWebService(string providerName, string url, string methodName, object[] args, WebClient wc = null)
        {
            object result = null;

            if (wc == null) wc = new WebClient();
            using (wc)
            {
                using (Stream wsdl = wc.OpenRead(url))
                {
                    var client = GetClient(wsdl, url, methodName, providerName);
                    client.SetValue("Timeout", wsdl.ReadTimeout);
                    result = client.InvokeService(args);
                }
            }

            return result;
        }

  形如这样 http://192.168.2.100:8090/services/dududuTest?wsdl 的地址,

  返回的是 dududuTest 服务下公开的方法,以流的形式,

  代码处理里面需要解读这种流,目前看到的一种方式是,把这个流解读编译成一个动态的dll,利用反射,动态调用方法。

ContractedBlock.gif ExpandedBlockStart.gif
    /// <summary>为从具有 <see cref="T:System.String" /> 指定的 URI 的资源下载的数据打开一个可读的流。</summary>
    /// <returns>一个 <see cref="T:System.IO.Stream" />,用于从资源读取数据。</returns>
    /// <param name="address">以 <see cref="T:System.String" /> 形式指定的 URI,将从中下载数据。</param>
    public Stream OpenRead(string address)
    {
      if (address == null)
        throw new ArgumentNullException(nameof (address));
      return this.OpenRead(this.GetUri(address));
    }

    /// <summary>为从具有 <see cref="T:System.Uri" /> 指定的 URI 的资源下载的数据打开一个可读的流</summary>
    /// <returns>一个 <see cref="T:System.IO.Stream" />,用于从资源读取数据。</returns>
    /// <param name="address">以 <see cref="T:System.Uri" /> 形式指定的 URI,将从中下载数据。</param>
    public Stream OpenRead(Uri address)
    {
      if (Logging.On)
        Logging.Enter(Logging.Web, (object) this, nameof (OpenRead), (object) address);
      if (address == (Uri) null)
        throw new ArgumentNullException(nameof (address));
      WebRequest request = (WebRequest) null;
      this.ClearWebClientState();
      try
      {
        request = this.m_WebRequest = this.GetWebRequest(this.GetUri(address));
        Stream responseStream = (this.m_WebResponse = this.GetWebResponse(request)).GetResponseStream();
        if (Logging.On)
          Logging.Exit(Logging.Web, (object) this, nameof (OpenRead), (object) responseStream);
        return responseStream;
      }
      catch (Exception ex)
      {
        Exception innerException = ex;
        if (innerException is ThreadAbortException || innerException is StackOverflowException || innerException is OutOfMemoryException)
        {
          throw;
        }
        else
        {
          if (!(innerException is WebException) && !(innerException is SecurityException))
            innerException = (Exception) new WebException(SR.GetString("net_webclient"), innerException);
          WebClient.AbortRequest(request);
          throw innerException;
        }
      }
      finally
      {
        this.CompleteWebClientState();
      }
    }
View Code

  类 DefaultWebServiceClient 定义:

ContractedBlock.gif ExpandedBlockStart.gif
    public class DefaultWebServiceClient
    {
        Type _type;
        MethodInfo _method;
        object _obj;

        public object InvokeService(object[] args)
        {
            object proxy = GetProxy();
            return _method.Invoke(proxy, args);
        }

        public void SetValue(string fieldName, object value)
        {
            object proxy = GetProxy();
            PropertyInfo field = _type.GetProperty(fieldName);
            if (field != null)
                field.SetValue(proxy, value);
        }

        public object GetProxy()
        {
            if (_obj == null)
                _obj = Activator.CreateInstance(_type);

            return _obj;
        }

        public MethodInfo MethodInfo
        {
            get { return _method; }
        }

        public DefaultWebServiceClient(Stream wsdl, string url, string methodname, string providerName)
        {
            if (wsdl == null || (wsdl.CanWrite && wsdl.Length == 0))
                throw new Exception("Wsdl为空");

            try
            {
                ServiceDescription sd = ServiceDescription.Read(wsdl);
                ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();
                sdi.AddServiceDescription(sd, "", "");
                CodeNamespace cn = new CodeNamespace(string.Format("DefaultWebServiceClient_{0}_{1}", providerName, wsdl.GetHashCode().ToString()));

                DiscoveryClientProtocol dcp = new DiscoveryClientProtocol();
                dcp.DiscoverAny(url);
                dcp.ResolveAll();
                foreach (object osd in dcp.Documents.Values)
                {
                    if (osd is ServiceDescription) sdi.AddServiceDescription((ServiceDescription)osd, null, null); ;
                    if (osd is XmlSchema) sdi.Schemas.Add((XmlSchema)osd);
                }

                //生成客户端代理类代码 
                CodeCompileUnit ccu = new CodeCompileUnit();
                ccu.Namespaces.Add(cn);
                sdi.Import(cn, ccu);
                CSharpCodeProvider csc = new CSharpCodeProvider();
                ICodeCompiler icc = csc.CreateCompiler();

                //设定编译器的参数 
                CompilerParameters cplist = new CompilerParameters();
                cplist.GenerateExecutable = false;
                cplist.GenerateInMemory = true;
                cplist.ReferencedAssemblies.Add("System.dll");
                cplist.ReferencedAssemblies.Add("System.XML.dll");
                cplist.ReferencedAssemblies.Add("System.Web.Services.dll");
                cplist.ReferencedAssemblies.Add("System.Data.dll");

                //编译代理类 
                CompilerResults cr = icc.CompileAssemblyFromDom(cplist, ccu);
                if (true == cr.Errors.HasErrors)
                {
                    System.Text.StringBuilder sb = new StringBuilder();
                    foreach (CompilerError ce in cr.Errors)
                    {
                        sb.Append(ce.ToString());
                        sb.Append(System.Environment.NewLine);
                    }
                    throw new Exception(sb.ToString());
                }

                //生成代理实例,并调用方法 
                Assembly assembly = cr.CompiledAssembly;
                Type type = null;
                foreach (Type t in assembly.GetExportedTypes())
                {
                    if (t.GetCustomAttributes(typeof(System.Web.Services.WebServiceBindingAttribute), false).Count() > 0)
                    {
                        type = t;
                        break;
                    }
                }

                MethodInfo mi = null;

                if (type == null)
                {
                    throw new Exception("从Wsdl中找不到可调用的类型");
                }

                mi = type.GetMethod(methodname);
                if (mi == null)
                {
                    throw new Exception(string.Format("从Wsdl中找不到可调用的方法{0}.{1}", type.Name, methodname));
                }
                _type = type;
                _method = mi;
            }
            catch (Exception ex)
            {
                throw new Exception("创建WebService客户端失败!", ex);
            }
        }
    }
View Code

  WebClient 是一个操作 WebRequest 的类型,相当于一个 worker,它把服务器能提供的内容(资源)都以流的形式返回来,供我们调用,

  解读这种流,需要 ServiceDescription 类实例,再将每项加载入 ServiceDescriptionImporter 类的实例中,

  再把它编译成能本地使用的组件,动态地调用,相当于运行时加载了一个dll。

  (注:三种方法调用 webService https://www.jb51.net/article/190211.htm

 

 

验证 1

验证 2

 

新建了一个webClient(服务代理),

它请求的处理对象默认是webRequest,

因为webRequest没有TimeOut属性,于是我继承了webCLient,override处理对象为HttpWebRequest

(注,HttpWebRequest 是 WebRequest的子类)

新建了一个webClient,

它请求的处理对象默认是webRequest

 

结果

在完成整个调用当中charles获取了2次http请求,其中:

第一次:在获取wsdl流的时候,请求包是http请求的get方式;

第二次:加载动态dll反射调用方法时,请求包是http请求的post方式;

同左

webClient真的是一个代理,像一个worker,代码上看似在本地动态引用了第三方的dll,但实际上还是http请求

就算不写死类型为 HttpWebRequest,识别出来的对象仍然是HttpWebRequest 的实例,这个服务本质提供的就是 http 请求

待证

 

识别为http请求应该是url的前缀是http的原因,如果是ftp://...那么识别出来就应该是ftpWebRequest

  这种 WebClient 的方式应该只适用于取 wsdl 来处理,

  我尝试直接用 HttpWebRequest 用 get 方法取 http://localhost/ESBService/VitalSign.svc?wsdl 的内容,返回了一段服务中的方法说明 xml,

  而我试过直接照着第二次包的请求内容来发 HttpWebRequest,并不能成功(报错500内部服务器出错),可能是我入参处理不对。

  WebClient 方式和直接发 HttpWebRequest 方式应该是互通的,可以互相转换的,

  不过 WebClient 使用 Httpwebrequest 的方式封装了别的处理,某些程度上减少了程序员的工作,总归是数据结构整合的问题,这块就不多研究了。

 

  WebClient封装 HttpWebRequest 的部分内容(头部等),它还提供了一些方法,

  这里有一个示例,是异步请求,得到响应后触发事件的适用,不过这个实例比较久远了,2008年的:

https://docs.microsoft.com/zh-cn/archive/blogs/silverlight_sdk/using-webclient-and-httpwebrequest

 

  .Net当中,WebRequest 与 HttpWebRequest 区别,从名字感觉很相似,反编译结果确实是。

由客服端构建的(不同协议的)请求发给服务器

WebRequest

FtpWebRequest

FileWebRequest

HttpWebRequest

WebSocket

抽象基类

继承于WebRequest

继承于WebRequest

继承于WebRequest

抽象基类

与WebResponse成对存在

ftp:// 开头

file:// 开头,一般是打开本机文件,

形如:

file:///C:/Users/dududu/0209.pdf

file://dududu/Share2021/

http:// 开头

ws:// 开头

wss:// 

 

 

 

Websocket主要是javaScript在页面中使用,不需要像http请求那样等待一整个页面文件返回,只取业务数据。

点击看看参考

 

   放一些地址给观察观察,感知请求和接受的运作模式,各有性格,殊途同归:

http://192.168.8.100:9000/empId=<EmployeeId>&jobId=<JobId>

get 方式,相当于有这样一个格式的服务地址,可以返回一个超文本内容(网页)或者一些某种格式的数据。

(我比较好奇是服务器怎么响应网络,光知道配置总显得苍白)

http://172.18.99.100:8080/yyzx/index.action?userName=<userName>&passWord=<passWord>

有些网址中这样是等价的,应该是哪里(服务配置、架构配置等)处理到了这个逻辑:

http://192.168.29.100:8081/emr/index.php/index/emr/getemr?personid=7321446

http://192.168.29.100:8081/emr/index.php/index/emr/getemr/personid/7321446

 

附:点击下载完整代码

 

原文地址:https://blog.csdn.net/qq_45534061/article/details/115469831

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


1.使用ajax调用varxhr;functioninvoke(){if(window.ActiveXObject){xhr=newActiveXObject("Microsoft.XMLHTTP");}else{xhr=newXMLHttpRequest();}//指定请求地址varurl="http://127.0.0.1:7777/hello?wsdl";//
               好不容易把WebService服务器端搭建起来,我们还需要客户端程序也同样跑起来才能够进行和服务器端程序的通信: 在这篇文章里面,我会先自己写代码去实现调用WebService服务器端程序,接下来,通过IDEA配置的方式来调用WebService服务端: 首先,我写了一个W
1新建一个工程项目用来做服务端增加一个MyService1类文件packagecom.zns.ws;importjavax.jws.WebMethod;importjavax.jws.WebService;importjavax.xml.ws.Endpoint;@WebServicepublicclassMyService1{publicstaticvoidmain(String[]args){
packagecom.transsion.util;importjava.io.BufferedReader;importjava.io.IOException;importjava.io.InputStreamReader;importjava.io.PrintWriter;importjava.net.URL;importjava.net.URLConnection;importcom.alibaba.druid.util.Base64;importcom.tra
再生产wsdl文件时重写描述文件1usingSystem;2usingSystem.Collections.Generic;3usingSystem.Linq;4usingSystem.Web;5usingSystem.Web.Services.Description;67namespaceStrongSoftManage.Web.App8{9publicclassSoapExtens:SoapExtensi
一般情况下,使用eclipse自带的jax-ws生成webservice会自动生成2个类:ContractConnector.java packagecom.wonders.webservice.contract;importjava.text.DecimalFormat;importjava.text.ParseException;importjava.text.SimpleDateFormat;importjava.util.Date;i
一、WebService概述1.1什么是WebService 基于Web的服务:服务器端整出一些资源让客户端应用访问(获取数据) 一个跨语言、跨平台的规范(抽象)所谓跨编程语言和跨操作平台,就是说服务端程序采用java编写,客户端程序则可以采用其他编程语言编写,反之亦然!跨操作系统平台则是指服务
一、什么是CXF?    ApacheCXF=Celtix+Xfire,开始叫ApacheCeltiXfire,后来更名为ApacheCXF了,以下简称为CXF。ApacheCXF是一个开源的webServices框架,CXF帮助您构建和开发webServices,它支持多种协议,比如:SOAP1.1,1,2 XML/HTTP、RESTful或者CORBA。  
工具IDEA一、构建项目1、选择SpringInitializr2、填写项目信息3、勾选webService4、勾选Thymeleaf5、项目建立完成,启动类自动生成二、写个Controller启动服务。浏览器访问/hello接口。 
1.环境win764位,vs20102.新建一个asp.netweb应用程序(同上一篇)3.添加一个web引用,引用上一篇创建的服务。注意不是服务引用。如下图 
WebService之WSDL文件讲解   恩,我想说的是,是不是经常有人在开发的时候,特别是和第三方有接口的时候,走的是SOAP协议,然后用户给你一个WSDL文件,说按照上面的进行适配,嘿嘿,这个时候,要是你以前没有开发过,肯定会傻眼,那如果你想学习的话,就认真的看下面的讲解咯:一、WSDL概述  
在websrvice发布文件的webconfig中加入<httpRuntimemaxRequestLength="102400"/> <webServices>     <protocols>       <addname="HttpPost"/>       <addname="HttpGet"/>     </protocols>   
 代码比较简单,按照如下来操作即可,只是jar包有很多问题,比如找不到classnotFondspring、以及找不到xfile.xml、以及xfile.xml中的一个参数问题,以及2.0 spring。jar和spring1.6.2冲突问题,总之这个小demo报了一堆错误,其实都是jar的问题,为了让大家减少这方面的错误,所以我提供
 一、soapUI简介SOAP:   WebService通过Http协议发送请求和接收结果时,发送的请求内容和结果内容都采用XML格式封装,并增加了一些特定的HTTP消息头,以说明HTTP消息头的内容格式,这些特定的HTTP消息头和XML内容格式就是SOAP协议。SOAP提供了标准的RPC方法来调用WebService。 
参考,感谢https://blog.csdn.net/hj7jay/article/details/727224381.环境:win764位,jdk1.8.0_201 EclipseJavaEEIDEforWebDevelopers.Version:Mars.1Release(4.5.1)2.创建一个普通的java项目,名字是TheService在src目录下创建一个com.hyan.service包,在此包下创建
CXF实现RestfulWebService基础示例一、写在前面IDE:IDEA14JDK:1.7CXF:2.6.2示例来源:%CXF_HOME%\samples\jax_rs\basic发布方式:JAXRSServerFactoryBean的create()方法调用方式:URL的openStream()方法、HttpClient的executeMethod()方法二、服务端(Java项目)1.准备Jar包
封装helper类:classWebServiceHelper{///<summary>///1.get请求http方法///</summary>///<paramname="url">基础url</param>///<paramname="method">请求方法</param>///<paramnam
.net客户端调用java或.netwebservice进行soapheader验证最近项目中有业务需要跨平台调用web服务,客户端和服务器之间采用非对称加密来保证数据的安全性,webservice的安全验证基于soapheader。借此机会,顺便整理一下调用.netwebservice和javawebservice的验证方式,记录下来。
Node.jshttps://www.cnblogs.com/goldlong/p/8027997.htmlQQ音乐apihttps://juejin.im/post/5a35228e51882506a463b172#heading-11?tdsourcetag=s_pcqq_aiomsgGit把本地仓库上传到GitHbubhttps://blog.csdn.net/zamamiro/article/details/70172900git删除本地仓库https://blog.cs
转载自:孤傲苍狼 WebService学习总结(三)——使用JDK开发WebService一、WebService的开发手段使用Java开发WebService时可以使用以下两种开发手段1、 使用JDK开发(1.6及以上版本)-->详见:本文2、使用CXF框架开发-->详见:其他文章二、使用JDK开发WebServi