C# 通过HttpWebRequest在后台对WebService进行调用
通过HttpWebRequest在后台对WebService进行调用
http://www.cnblogs.com/macroxu-1982/archive/2009/12/23/1630415.html
http://www.oschina.net/code/snippet_188227_8068
using System;
using System.Web;
using System.Xml;
using System.Collections;
using System.Net;
using System.Text;
using System.IO;
using System.Xml.Serialization; //By huangz 2008-3-19 /// <summary>
/// 利用WebRequest/WebResponse进行WebService调用的类 /// </summary>
public class WebSvcCaller
{
//<webServices>
// <protocols>
// <add name="HttpGet"/>
// <add name="HttpPost"/>
// </protocols>
//</webServices> private static Hashtable _xmlNamespaces = new Hashtable();//缓存xmlNamespace,避免重复调用GetNamespace /// <summary>
/// 需要WebService支持Post调用
/// </summary>
public static XmlDocument QueryPostWebService(String URL, String MethodName, Hashtable Pars)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.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支持Get调用
/// </summary>
public static XmlDocument QueryGetWebService(String URL, String MethodName, Hashtable Pars)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL + "/" + MethodName + "?" + ParsToString(Pars));
request.Method = "GET";
request.ContentType = "application/x-www-form-urlencoded";
SetWebRequest(request);
return ReadXmlResponse(request.GetResponse());
} /// <summary>
/// 通用WebService调用(Soap),参数Pars为String类型的参数名、参数值
/// </summary>
public static XmlDocument QuerySoapWebService(String URL, String MethodName, Hashtable Pars)
{
if (_xmlNamespaces.ContainsKey(URL))
{
return QuerySoapWebService(URL, MethodName, Pars, _xmlNamespaces[URL].ToString());
}
else
{
return QuerySoapWebService(URL, MethodName, Pars, GetNamespace(URL));
}
} private static XmlDocument QuerySoapWebService(String URL, String MethodName, Hashtable Pars, string XmlNs)
{
_xmlNamespaces[URL] = XmlNs;//加入缓存,提高效率
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL);
request.Method = "POST";
request.ContentType = "text/xml; charset=utf-8";
request.Headers.Add("SOAPAction", "\"" + XmlNs + (XmlNs.EndsWith("/") ? "" : "/") + MethodName + "\"");
SetWebRequest(request);
byte[] data = EncodeParsToSoap(Pars, XmlNs, MethodName);
WriteRequestData(request, data);
XmlDocument doc = new XmlDocument(), doc2 = new XmlDocument();
doc = ReadXmlResponse(request.GetResponse()); XmlNamespaceManager mgr = new XmlNamespaceManager(doc.NameTable);
mgr.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/");
String RetXml = doc.SelectSingleNode("//soap:Body/*/*", mgr).InnerXml;
doc2.LoadXml("<root>" + RetXml + "</root>");
AddDelaration(doc2);
return doc2;
}
private static string GetNamespace(String URL)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL + "?WSDL");
SetWebRequest(request);
WebResponse response = request.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
XmlDocument doc = new XmlDocument();
doc.LoadXml(sr.ReadToEnd());
sr.Close();
return doc.SelectSingleNode("//@targetNamespace").Value;
}
private static byte[] EncodeParsToSoap(Hashtable Pars, String XmlNs, String MethodName)
{
XmlDocument 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_x_x("soap", "Body", "http://schemas.xmlsoap.org/soap/envelope/");
XmlElement soapMethod = doc.createElement_x_x(MethodName);
soapMethod.SetAttribute("xmlns", XmlNs);
foreach (string k in Pars.Keys)
{
XmlElement soapPar = doc.createElement_x_x(k);
soapPar.InnerXml = ObjectToSoapXml(Pars[k]);
soapMethod.appendChild_xss(soapPar);
}
soapBody.appendChild_xss(soapMethod);
doc.DocumentElement.appendChild_xss(soapBody);
return Encoding.UTF8.GetBytes(doc.OuterXml);
}
private static string ObjectToSoapXml(object o)
{
XmlSerializer mySerializer = new XmlSerializer(o.GetType());
MemoryStream ms = new MemoryStream();
mySerializer.Serialize(ms, o);
XmlDocument doc = new XmlDocument();
doc.LoadXml(Encoding.UTF8.GetString(ms.ToArray()));
if (doc.DocumentElement != null)
{
return doc.DocumentElement.InnerXml;
}
else
{
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;
Stream writer = request.GetRequestStream();
writer.Write(data, , data.Length);
writer.Close();
} private static byte[] EncodePars(Hashtable Pars)
{
return Encoding.UTF8.GetBytes(ParsToString(Pars));
} private static String ParsToString(Hashtable Pars)
{
StringBuilder sb = new StringBuilder();
foreach (string k in Pars.Keys)
{
if (sb.Length > )
{
sb.Append("&");
}
//sb.Append(HttpUtility.UrlEncode(k) + "=" + HttpUtility.UrlEncode(Pars[k].ToString()));
}
return sb.ToString();
} private static XmlDocument ReadXmlResponse(WebResponse response)
{
StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
String retXml = sr.ReadToEnd();
sr.Close();
XmlDocument doc = new XmlDocument();
doc.LoadXml(retXml);
return doc;
} private static void AddDelaration(XmlDocument doc)
{
XmlDeclaration decl = doc.CreateXmlDeclaration("1.0", "utf-8", null);
doc.InsertBefore(decl, doc.DocumentElement);
}
} 调用示例: Hashtable ht = new Hashtable();
ht.Add("str", "test");
ht.Add("b", "true");
XmlDocument xx = WebSvcCaller.QuerySoapWebService("http://localhost:81/service.asmx", "HelloWorld", ht);
MessageBox.Show(xx.OuterXml);
C# 通过HttpWebRequest在后台对WebService进行调用的更多相关文章
- 通过HttpWebRequest在后台对WebService进行调用
目录: 1 后台调用Webservice的业务需求 2 WebService支持的交互协议 3 如何配置WebService支持的协议 4 后台对WebService的调用 4.1 SOAP 1.1 ...
- 在后台对GameObject进行"创建"||"删除"动作
在后台对GameObject进行"创建"||"删除"动作 建立 public GameObject Pre;//在编辑器中用来绑定的Prefabs public ...
- C# WebService动态调用
前言 站在开发者的角度,WebService 技术确实是不再“时髦”.甚至很多人会说,我们不再用它.当然,为了使软件可以更简洁,更有层次,更易于实现缓存等机制,我是非常建议将 SOAP 转为 REST ...
- WebService服务调用方法介绍
1 背景概述 由于在项目中需要多次调用webservice服务,本文主要总结了一下java调用WebService常见的6种方式,即:四种框架的五种调用方法以及使用AEAI ESB进行调用的方法. 2 ...
- [转贴]C++、C#写的WebService相互调用
以下宏文(原文在 http://blog.sina.com.cn/s/blog_4e7d38260100ade4.html),是转贴并进行了修饰编辑: 首先感谢永和兄提供C++的WebService服 ...
- python通过http请求发送soap报文进行webservice接口调用
最近学习Python调用webservice 接口,开始的时候主要采用suds 的方式生产client调用,后来发现公司的短信接口采用的是soap报文来调用的,然后开始了谷歌,最后采用httplib ...
- 根据wsdl文件,Java工程自动生成webservice客户端调用
根据wsdl文件,Java工程自动生成webservice客户端调用 1,工具:带有webservice插件的myeclips 2,步骤: (1),新建一个Java工程:relationship (2 ...
- 浅谈WebService的调用<转>
0.前言 前段时间,公司和电信有个合作,产品对接电信的某个平台,使用了WebService接口的调用,实现了业务受理以及单点登录.终于使用到了WebService,楼主还是比较兴奋的,目前功能已经上线 ...
- 根据wsdl的url,使用axis1.4生成客户端,并且对webservice进行调用(转)
根据wsdl的url,使用axis1.4生成客户端,并且对webservice进行调用 axis1.4下载地址 1.到www.apache.org上去下载axis-bin-1_4.zip,如要关联源代 ...
随机推荐
- Nginx源码分析-ngx_module_s结构体
该结构体是整个Nginx模块化架构最基本的数据结构体.它描述了Nginx程序中一个模块应该包括的基本属性,在tengine/src/core/ngx_conf_file.h中定义了该结构体 struc ...
- python_异常处理
常用异常种类 AttributeError 试图访问一个对象没有的树形,比如foo.x,但是foo没有属性x IOError 输入/输出异常:基本上是无法打开文件 ImportError 无法引入模块 ...
- HDU 4725 The Shortest Path in Nya Graph(spfa+虚拟点建图)
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4725 题目大意:有n层,n个点分布在这些层上,相邻层的点是可以联通的且距离为c,还有额外给出了m个条边 ...
- csu 1555(线段树经典插队模型-根据逆序数还原序列)
1555: Inversion Sequence Time Limit: 2 Sec Memory Limit: 256 MBSubmit: 469 Solved: 167[Submit][Sta ...
- linux下c图形化编程之gtk+2.0简单学习
在linux下想做一个图形化的界面,然后自己选择使用gtk+2.0来进行编辑,我的电脑已经安装过gtk+2.0了,所以就在网上找了一个安装方法,结果未测试,大家有安装问题可以说下,一起探讨下. 1.安 ...
- git rebase 过程中遇到冲突该怎么解决?
在执行git rebase 过程中经常遇到问题,此时有点慌,一般如何解决呢? 1.先将本地的冲突手动解决 2.执行下面命令 git add . git rebase --contine //继续re ...
- IEEEXtreme 10.0 - N-Palindromes
这是 meelo 原创的 IEEEXtreme极限编程大赛题解 Xtreme 10.0 - N-Palindromes 题目来源 第10届IEEE极限编程大赛 https://www.hackerra ...
- 搭建简单的CGI应用程序
原文来源于<核心编程3>第10章web编程 一.静态文件+脚本文件 1.首先开启cgiweb服务器 python2 -m CGIHTTPServer 8000 看到如下反应 2.服务器目录 ...
- [实战]MVC5+EF6+MySql企业网盘实战(9)——编辑文件名
写在前面 上篇文章实现了文件的下载,本篇文章将实现编辑文件名的功能. 系列文章 [EF]vs15+ef6+mysql code first方式 [实战]MVC5+EF6+MySql企业网盘实战(1) ...
- mac如何运行vue项目
由于本人使用的是mac系统,因此在vue.js 的环境搭建上遇到许许多多的坑.感谢 showonne.yubang 技术指导,最终成功解决.下面是个人的搭建过程,权当是做个笔记吧. 由于mac非常人性 ...