C# 通過模擬http請求來調用soap、wsdl


 

C#調用webservice的方法很多,我說的這種通過http請求模擬來調用的方式是為了解決C#調用java的遠程API出現各種不兼容問題。

由於遠程API不在我們的控制下,我們只能修改本地的調用代碼來適應遠程API。

在以上情況下,我們就通過模擬http請求來去調用webservice。

 

首先,我們要分析調用端口時,我們發送出去的數據。

先抓個包看看,這里,我們沒有辦法用Fiddler來監聽SOAP協議的內容,但是SOAP還是基於http協議的。

用更底層的工具是能夠抓到的。這里可以去百度一下,工具很多。

不過我找了一個java寫的,監聽SOAP協議的小工具。《戳我下載》http://download.csdn.net/detail/a406502972/9460758

抓到包了之后,直接post就行了,簡單易懂,直接上代碼:

 1         static string data = @"發送的內容";
 2         private static string contentType = "text/xml; charset=UTF-8";
 3         private static string accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/x-silverlight, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-ms-application, application/x-ms-xbap, application/vnd.ms-xpsdocument, application/xaml+xml, application/x-silverlight-2-b1, */*";
 4         private static string userAgent = "Axis2";
 5         /// <summary>
 6         /// 提交數據
 7         /// </summary>
 8         /// <param name="url"></param>
 9         /// <param name="cookie"></param>
10         /// <param name="param"></param>
11         /// <returns></returns>
12         public static string PostWebContent(string url, CookieContainer cookie, string param) {
13             byte[] bs = Encoding.ASCII.GetBytes(param);
14             var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
15             httpWebRequest.CookieContainer = cookie;
16             httpWebRequest.ContentType = contentType;
17             httpWebRequest.Accept = accept;
18             httpWebRequest.UserAgent = userAgent;
19             httpWebRequest.Method = "POST";
20             httpWebRequest.ContentLength = bs.Length;
21             using (Stream reqStream = httpWebRequest.GetRequestStream()) {
22                 reqStream.Write(bs, 0, bs.Length);
23             }
24             var httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
25             Stream responseStream = httpWebResponse.GetResponseStream();
26             string html = "";
27             if (responseStream != null) {
28                 StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8);
29                 html = streamReader.ReadToEnd();
30                 streamReader.Close();
31                 responseStream.Close();
32                 httpWebRequest.Abort();
33                 httpWebResponse.Close();
34             }
35             return html;
36         }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM