WebServiceCaller

 /*  jonney 2015-09-19 */

 using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml;
using System.Xml.Serialization; namespace Downloader
{
/// <summary>
/// 利用WebRequest/WebResponse进行WebService调用的类
/// </summary>
public class WebServiceCaller
{
/// <summary>
/// 需要WebService支持Get调用
/// </summary>
public static XmlDocument QueryGetWebService(String url, String methodName, Dictionary<string, object> pars)
{
var request = (HttpWebRequest)WebRequest.Create(url + "/" + methodName + "?" + ParsToString(pars));
request.Method = "GET";
request.ContentType = "application/x-www-form-urlencoded";
SetWebRequest(request);
return ReadXmlResponse(request.GetResponse());
} /// <summary>
/// 需要WebService支持Post调用
/// </summary>
public static XmlDocument QueryPostWebService(String url, String methodName, Dictionary<string, object> pars)
{
var request = (HttpWebRequest)WebRequest.Create(url + "/" + methodName);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded;";
SetWebRequest(request);
byte[] data = EncodePars(pars);
WriteRequestData(request, data);
return ReadXmlResponse(request.GetResponse());
} /// <summary>
/// 通用WebService调用(Soap),参数Pars为String类型的参数名、参数值
/// </summary>
public static XmlDocument QuerySoapWebService(String url, String methodName, Dictionary<string, object> pars)
{
if (XmlNamespaces.ContainsKey(url + methodName))
{
string[] echo = XmlNamespaces[url + methodName].ToString().Split('`');
string xmlNs = echo[];
string xmlSoapAction = echo[];
return QuerySoapWebService(url, methodName, pars, xmlNs, xmlSoapAction);
}
string soapAction = "";
string nameSpace = GetNamespace(url, methodName, ref soapAction);
return QuerySoapWebService(url, methodName, pars, nameSpace, soapAction);
} /// <summary>
/// 需要WebService支持Post调用,返回Json
/// </summary>
public static string QueryPostWebService(String endPoint, StringBuilder postData)
{
var request = (HttpWebRequest)WebRequest.Create(endPoint);
request.Method = "POST";
request.ContentType = "application/json";
SetWebRequest(request);
byte[] data = Encoding.UTF8.GetBytes(postData.ToString());
WriteRequestData(request, data);
return ReadTxtResponse(request.GetResponse());
} /// <summary>
/// 需要WebService支持Post调用,返回字节流
/// </summary>
public static byte[] QueryPostWebService(String endPoint, string postData)
{
var request = (HttpWebRequest)WebRequest.Create(endPoint);
request.Method = "POST";
request.ContentType = "application/json";
SetWebRequest(request);
byte[] data = Encoding.UTF8.GetBytes(postData);
WriteRequestData(request, data); using (var response = (HttpWebResponse)request.GetResponse())
{
if (response.StatusCode != HttpStatusCode.OK)
{
var message = String.Format(CultureInfo.CurrentCulture, "Request failed. Received HTTP {0}", response.StatusCode);
throw new WebException(message);
}
using (var result = new MemoryStream())
{
const int bufferLen = ;
var buffer = new byte[bufferLen];
using (var responseStream = response.GetResponseStream())
{
var len = responseStream.Read(buffer, , bufferLen);
while (len > )
{
result.Write(buffer, , len);
len = responseStream.Read(buffer, , bufferLen);
}
}
return result.ToArray();
}
}
} private static XmlDocument QuerySoapWebService(String url, String methodName, Dictionary<string, object> pars, string xmlNs, string soapAction)
{
XmlNamespaces[url + methodName] = xmlNs + "`" + soapAction;//加入缓存,提高效率
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "text/xml; charset=utf-8;";
string temSoapAction = "\"" + soapAction + "\"";
request.Headers.Add("SOAPAction", temSoapAction);
SetWebRequest(request);
byte[] data = EncodeParsToSoap(pars, xmlNs, methodName);
WriteRequestData(request, data);
var doc2 = new XmlDocument();
XmlDocument doc = ReadXmlResponse(request.GetResponse());
var mgr = new XmlNamespaceManager(doc.NameTable);
mgr.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/");
var xmlNode = doc.SelectSingleNode("//soap:Body/*", mgr);
if (xmlNode != null)
{
String retXml = xmlNode.InnerXml;
doc2.LoadXml("<root>" + retXml + "</root>");
}
else throw new SystemException("Get soap:Body null");
AddDelaration(doc2);
return doc2;
} private static string GetNamespace(String url, string method, ref string pSoapAction)
{
var doc = new XmlDocument();
var request = (HttpWebRequest)WebRequest.Create(url + "?wsdl");
SetWebRequest(request);
using (var response = (HttpWebResponse)request.GetResponse())
{
if (response.StatusCode != HttpStatusCode.OK)
{
var message = String.Format(CultureInfo.CurrentCulture, "Request failed. Received HTTP {0}", response.StatusCode);
throw new SystemException(message);
}
using (var responseStream = response.GetResponseStream())
{
if (responseStream != null)
{
using (var sr = new StreamReader(responseStream, Encoding.UTF8))
{
doc.LoadXml(sr.ReadToEnd());
}
}
else throw new SystemException("GetNamespace url error");
}
}
var xmlNode = doc.SelectSingleNode("//@targetNamespace");
XmlNodeList soapActionList = doc.SelectNodes("//@soapAction");
if (soapActionList!=null)
{
for (int i = ; i < soapActionList.Count; i++)
{
var item = soapActionList.Item(i);
if (item != null && item.Value.EndsWith("/" + method))
{
pSoapAction = item.Value;
}
}
}
if (xmlNode != null)
return xmlNode.Value;
throw new SystemException("GetNamespace xmlNode null");
} private static byte[] EncodeParsToSoap(Dictionary<string, object> pars, String xmlNs, String methodName)
{
var doc = new XmlDocument();
doc.LoadXml("<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"></soap:Envelope>");
AddDelaration(doc);
XmlElement soapBody = doc.CreateElement("soap", "Body", "http://schemas.xmlsoap.org/soap/envelope/");
XmlElement soapMethod = doc.CreateElement(methodName);
soapMethod.SetAttribute("xmlns", xmlNs);
foreach (string k in pars.Keys)
{
XmlElement soapPar = doc.CreateElement(k);
soapPar.InnerXml = ObjectToSoapXml(pars[k]);
soapMethod.AppendChild(soapPar);
}
soapBody.AppendChild(soapMethod);
if (doc.DocumentElement != null) doc.DocumentElement.AppendChild(soapBody);
return Encoding.UTF8.GetBytes(doc.OuterXml);
} private static string ObjectToSoapXml(object o)
{
var doc = new XmlDocument();
var mySerializer = new XmlSerializer(o.GetType());
using (var ms = new MemoryStream())
{
mySerializer.Serialize(ms, o);
doc.LoadXml(Encoding.UTF8.GetString(ms.ToArray(), , (int)ms.Length));
}
if (doc.DocumentElement != null)
{
return doc.DocumentElement.InnerXml;
}
return o.ToString();
} private static void SetWebRequest(HttpWebRequest request)
{
request.Credentials = CredentialCache.DefaultCredentials;
request.Timeout = ;
} private static void WriteRequestData(HttpWebRequest request, byte[] data)
{
request.ContentLength = data.Length;
using (Stream writer = request.GetRequestStream())
{
writer.Write(data, , data.Length);
}
} private static byte[] EncodePars(Dictionary<string, object> pars)
{
var sb = new StringBuilder();
sb.Append("{");
foreach (string k in pars.Keys)
{
if (sb.Length > )
{
sb.Append(",");
}
sb.Append("\"" + k + "\"" + ":" + "\"" + pars[k] + "\"");
}
sb.Append("}");
return Encoding.UTF8.GetBytes(sb.ToString());
} private static String ParsToString(Dictionary<string, object> pars)
{
var sb = new StringBuilder();
foreach (string k in pars.Keys)
{
if (sb.Length > )
{
sb.Append("&");
}
sb.Append(k + "=" + pars[k]);
}
return sb.ToString();
} private static XmlDocument ReadXmlResponse(WebResponse resp)
{
var doc = new XmlDocument();
using (var response = (HttpWebResponse)resp)
{
if (response.StatusCode != HttpStatusCode.OK)
{
var message = String.Format(CultureInfo.CurrentCulture, "Request failed. Received HTTP {0}", response.StatusCode);
throw new SystemException(message);
}
using (var responseStream = resp.GetResponseStream())
{
if (responseStream != null)
using (var sr = new StreamReader(responseStream, Encoding.UTF8))
{
doc.LoadXml(sr.ReadToEnd());
}
}
}
return doc;
} private static string ReadTxtResponse(WebResponse resp)
{
using (var response = (HttpWebResponse)resp)
{
var responseValue = string.Empty;
if (response.StatusCode != HttpStatusCode.OK)
{
var message = String.Format(CultureInfo.CurrentCulture, "Request failed. Received HTTP {0}", response.StatusCode);
throw new SystemException(message);
}
using (var responseStream = response.GetResponseStream())
{
if (responseStream != null)
using (var sr = new StreamReader(responseStream, Encoding.UTF8))
{
responseValue = sr.ReadToEnd();
}
}
return responseValue;
}
} private static void AddDelaration(XmlDocument doc)
{
XmlDeclaration decl = doc.CreateXmlDeclaration("1.0", "utf-8", null);
doc.InsertBefore(decl, doc.DocumentElement);
} private static readonly Hashtable XmlNamespaces = new Hashtable();//缓存xmlNamespace,避免重复调用GetNamespace
}
}

WebServiceCaller的更多相关文章

  1. C# 调用webservice 几种办法(转载)

    原文地址: http://www.cnblogs.com/eagle1986/archive/2012/09/03/2669699.html //=========================== ...

  2. C# WebServices中处理XML方式

    1.企业系统集成的时候,大量的字段是很麻烦处理的,用Format 的方式可快速处理 string sql = @"SELECT * FROM table WHERE TASKID='&quo ...

  3. 调用webservice 总结

    最近做一个项目,由于是在别人框架里开发app,导致了很多限制,其中一个就是不能直接引用webservice . 我们都知道,调用webserivice 最简单的方法就是在 "引用" ...

  4. 使用vs2010创建、发布、部署、调用 WebService

    原文地址:使用vs2010创建.发布.部署.调用 WebService作者:吴超 一 使用vs2010创建 WebService 1 打开VS2010,菜单    文件->新建->项目2 ...

  5. C#动态webservice调用接口 (JAVA,C#)

    C#动态webservice调用接口 using System; using System.Collections; using System.IO; using System.Net; using ...

  6. .net 调用webservice 总结

    最近做一个项目,由于是在别人框架里开发app,导致了很多限制,其中一个就是不能直接引用webservice . 我们都知道,调用webserivice 最简单的方法就是在 "引用" ...

  7. asp.net访问WebService的各种方式

    WebService的访问形式主要有:SOAP调用.XMLHTTP POST.GET调用.MicroSoft.XMLDOMC调用.webbehavior.htc调用 我们知道的在C#后台本地调用Web ...

  8. WebService 调用三种方法

    //来源:http://www.cnblogs.com/eagle1986/archive/2012/09/03/2669699.html 最近做一个项目,由于是在别人框架里开发app,导致了很多限制 ...

  9. webservice的两种调用方式

    如下 using ConsoleApplication1.TestWebService; using System; using System.Collections; using System.Co ...

随机推荐

  1. hibernate hibernate.cfg.xml component 组件

    1.为什么使用component组件? 当一个表的列数目比较多时,可以根据属性分类,将一个java对象拆分为几个对象. 数据库还是一张表,不过有多个对象与之对应. 2.实例 2.1 Java 对象: ...

  2. 由两点坐标如何画出直线 matlab

    由两点坐标如何画出直线  方法1:利用直线方程 斜率加截距 方法2:数据拟合 %由两点坐标得数据拟合直线与画线 x = [,]; y = [,]; k = ((-)/(-));% 由两点坐标得到直线斜 ...

  3. OneSQL的docker之旅

      百度盘下载地址: http://pan.baidu.com/s/1v9GWA   OneSQL Docker使用方法:  1. 解压    tar zxvf OneSql-Docker-5.6.2 ...

  4. 习题-第5章Web自动化测试

    一.选择题 二.判断题 三.填空题 四.简答题 五.设计题

  5. iOS开发UI篇—UITableviewcell的性能优化和缓存机制

    iOS开发UI篇—UITableviewcell的性能问题 一.UITableviewcell的一些介绍 UITableView的每一行都是一个UITableViewCell,通过dataSource ...

  6. css伪元素选择器(伪对象选择器)checked + 伪元素练习

    伪对象也叫伪元素,在过去,伪类和伪元素都被书写成前面只加一个冒号,实际上应该是: :weilei ::伪元素 而现在我们为了兼容旧的书写方式,用一个冒号引导伪类也是能被解析的. 伪类一般反应无法在CS ...

  7. 一块神奇的树莓派电子板竟让我学会了Linux系统

    树莓派(Raspberry Pi)是基于ARM的微型电脑主板,外形只有信用卡大小,因此也被称为新型卡片式电脑,树莓派具有电脑的所有基本功能,可谓麻雀虽小五脏俱全.而其开发组织Raspberry Pi ...

  8. INSTALL_FAILED_INSUFFICIENT_STORAGE

    现象:运行程序,进行安装时,ANDROID模拟器启动失败,在Eclipse的控制台里log显示如下错误信息     Installation error: INSTALL_FAILED_INSUFFI ...

  9. JavaScript中的逗号运算符

    JavaScript逗号运算符  阅读本文的前提,明确表达式.短语.运算符.运算数这几个概念. 所谓表达式,就是一个JavaScript的“短语”,JavaScript解释器可以计算它,从而生成一个值 ...

  10. Nginx反向代理关于端口的问题

      Nginx反向代理关于端口的问题   http://www.cnblogs.com/likehua/p/4056625.html Nginx默认反向后的端口为80,因此存在被代理后的端口为80的问 ...