日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > C# >内容正文

C#

C# WebClient调用WebService

發布時間:2025/3/8 C# 61 如意码农
生活随笔 收集整理的這篇文章主要介紹了 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,利用反射,動態調用方法。

    /// <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();
}
}

  類 DefaultWebServiceClient 定義:

    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);
}
}
}

  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

附:點擊下載完整代碼

總結

以上是生活随笔為你收集整理的C# WebClient调用WebService的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。