C# 通过模拟http请求来调用soap、wsdl

时间:2021-08-27 02:33:51

C#调用webservice的方法很多,我说的这种通过http请求模拟来调用的方式是为了解决C#调用java的远程API出现各种不兼容问题。

由于远程API不在我们的控制下,我们只能修改本地的调用代码来适应远程API。

在以上情况下,我们就通过模拟http请求来去调用webservice。

首先,我们要分析调用端口时,我们发送出去的数据。

先抓个包看看,这里,我们没有办法用Fiddler来监听SOAP协议的内容,但是SOAP还是基于http协议的。

用更底层的工具是能够抓到的。这里可以去百度一下,工具很多。

不过我找了一个java写的,监听SOAP协议的小工具。《戳我下载》http://download.csdn.net/detail/a406502972/9460758

C# 通过模拟http请求来调用soap、wsdl

抓到包了之后,直接post就行了,简单易懂,直接上代码:

         static string data = @"发送的内容";
private static string contentType = "text/xml; charset=UTF-8";
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, */*";
private static string userAgent = "Axis2";
/// <summary>
/// 提交数据
/// </summary>
/// <param name="url"></param>
/// <param name="cookie"></param>
/// <param name="param"></param>
/// <returns></returns>
public static string PostWebContent(string url, CookieContainer cookie, string param) {
byte[] bs = Encoding.ASCII.GetBytes(param);
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.CookieContainer = cookie;
httpWebRequest.ContentType = contentType;
httpWebRequest.Accept = accept;
httpWebRequest.UserAgent = userAgent;
httpWebRequest.Method = "POST";
httpWebRequest.ContentLength = bs.Length;
using (Stream reqStream = httpWebRequest.GetRequestStream()) {
reqStream.Write(bs, , bs.Length);
}
var httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
Stream responseStream = httpWebResponse.GetResponseStream();
string html = "";
if (responseStream != null) {
StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8);
html = streamReader.ReadToEnd();
streamReader.Close();
responseStream.Close();
httpWebRequest.Abort();
httpWebResponse.Close();
}
return html;
}