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 }
作者:愤怒的TryCatch
请尊重别人的劳动成果,让分享成为一种美德,欢迎转载。另外,文章在表述和代码方面如有不妥之处,欢迎批评指正。留下你的脚印,欢迎评论!