c# 请求webservice

1、封装后的类

  1 /// <summary>
  2     /// 自定义的请求WebService类
  3     /// </summary>
  4     public class WebServiceRequest
  5     {
  6         private string url = "";
  7         private int timeOut = 180000;
  8         private string requestText = "";
  9         private string method = "Post";
 10         private string contentType = "text/xml; charset=utf-8";
 11         private string responseText = "";
 12         private string statusText = "";
 13
 14         private bool synchronous = false;
 15
 16         public delegate void RequestEventHandler(object sender, EventArgs e);
 17
 18         public event RequestEventHandler RequestComplete;
 19
 20         protected virtual void OnRequestComplete(EventArgs e)
 21         {
 22             if (RequestComplete != null)
 23             {
 24                 RequestComplete(this, e);
 25             }
 26         }
 27
 28         public bool Synchronous
 29         {
 30             get
 31             {
 32                 return synchronous;
 33             }
 34             set
 35             {
 36                 synchronous = value;
 37             }
 38         }
 39
 40         public string ContentType
 41         {
 42             get
 43             {
 44                 return contentType;
 45             }
 46             set
 47             {
 48                 contentType = value;
 49             }
 50         }
 51
 52         public string Method
 53         {
 54             get
 55             {
 56                 return method;
 57             }
 58             set
 59             {
 60                 method = value;
 61             }
 62         }
 63         /// <summary>
 64         /// 设置web服务地址
 65         /// </summary>
 66         public string Url
 67         {
 68             get
 69             {
 70                 return url;
 71             }
 72             set
 73             {
 74                 url = value;
 75             }
 76         }
 77         /// <summary>
 78         /// 设置请求webservice的参数(XML)
 79         /// </summary>
 80         public string RequestText
 81         {
 82             get
 83             {
 84                 return requestText;
 85             }
 86             set
 87             {
 88                 requestText = value;
 89             }
 90         }
 91
 92
 93         public int TimeOut
 94         {
 95             get
 96             {
 97                 return timeOut;
 98             }
 99             set
100             {
101                 timeOut = value;
102             }
103         }
104
105         public string StatusText
106         {
107             get
108             {
109                 return statusText;
110             }
111         }
112         /// <summary>
113         /// webservice返回的信息
114         /// </summary>
115         public string ResponseText
116         {
117             get
118             {
119                 return responseText;
120             }
121         }
122
123         /// <summary>
124         /// 将xml字符串载入xml文档
125         /// </summary>
126         public XmlDocument ResponseXml
127         {
128             get
129             {
130                 XmlDocument xmlDocument = new XmlDocument();
131                 xmlDocument.LoadXml(this.ResponseText);
132                 return xmlDocument;
133             }
134         }
135
136         private void OnRequestStream(IAsyncResult asyncResult)
137         {
138             try
139             {
140                 HttpWebRequest httpWebRequest = (HttpWebRequest)asyncResult.AsyncState;
141                 httpWebRequest.EndGetRequestStream(asyncResult);
142                 byte[] datas = System.Text.Encoding.UTF8.GetBytes(this.RequestText);
143                 using (Stream writer = httpWebRequest.GetRequestStream())
144                 {
145                     writer.Write(datas, 0, datas.Length);
146                 }
147                 httpWebRequest.BeginGetResponse(new AsyncCallback(OnResponseStream), httpWebRequest);
148
149             }
150             catch (Exception exception)
151             {
152                 this.statusText = exception.Message;
153                 OnRequestComplete(new EventArgs());
154             }
155         }
156
157         private void OnResponseStream(IAsyncResult asyncResult)
158         {
159             HttpWebRequest httpWebRequest;
160             HttpWebResponse httpWebResponse = null;
161             try
162             {
163                 httpWebRequest = (HttpWebRequest)asyncResult.AsyncState;
164                 httpWebRequest.EndGetResponse(asyncResult);
165                 httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
166                 using (Stream responseStream = httpWebResponse.GetResponseStream())
167                 {
168                     using (StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8))
169                     {
170                         this.responseText = streamReader.ReadToEnd();
171                         OnRequestComplete(new EventArgs());
172                     }
173                 }
174                 httpWebResponse.Close();
175             }
176             catch (Exception exception)
177             {
178                 this.statusText = exception.Message;
179                 OnRequestComplete(new EventArgs());
180             }
181             finally
182             {
183                 if (httpWebResponse != null) httpWebResponse.Close();
184             }
185         }
186
187
188         /// <summary>
189         /// 开始请求
190         /// </summary>
191         public void Start()
192         {
193
194             try
195             {
196                 HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(this.Url);
197                 httpWebRequest.Timeout = this.TimeOut;
198                 httpWebRequest.ReadWriteTimeout = this.TimeOut;
199                 httpWebRequest.Method = this.Method;
200                 httpWebRequest.ContentType = this.ContentType;
201                 if (this.Synchronous)
202                 {
203                     #region
204                     if (this.RequestText.Length > 0)
205                     {
206                         httpWebRequest.BeginGetRequestStream(new AsyncCallback(OnRequestStream), httpWebRequest);
207                     }
208                     else
209                     {
210                         httpWebRequest.BeginGetResponse(new AsyncCallback(OnResponseStream), httpWebRequest);
211                     }
212                     #endregion
213                 }
214                 else
215                 {
216                     if (this.RequestText.Length > 0)
217                     {
218                         byte[] datas = System.Text.Encoding.UTF8.GetBytes(this.RequestText);
219                         using (Stream writer = httpWebRequest.GetRequestStream())
220                         {
221                             writer.Write(datas, 0, datas.Length);
222                         }
223                     }
224                     HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
225                     using (Stream responseStream = httpWebResponse.GetResponseStream())
226                     {
227                         using (StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8))
228                         {
229                             this.responseText = streamReader.ReadToEnd();
230                             OnRequestComplete(new EventArgs());
231                         }
232                     }
233                     httpWebResponse.Close();
234                 }
235             }
236             catch (Exception exception)
237             {
238                 this.statusText = exception.Message;
239                 OnRequestComplete(new EventArgs());
240             }
241
242         }
243
244         /// <summary>
245         /// 解析回执xml为DataSet
246         /// </summary>
247         /// <param name="xmlString"></param>
248         /// <returns></returns>
249         public DataSet resolvingXml(string xmlString)
250         {
251             DataSet ds = new DataSet();
252             XmlReader xmlReader = null;
253             try
254             {
255                 UTF8Encoding utf8 = new UTF8Encoding();
256                 byte[] bytes = utf8.GetBytes(xmlString);
257                 MemoryStream memortyStream = new MemoryStream();
258                 memortyStream.Seek(0, SeekOrigin.Begin);
259                 memortyStream.Write(bytes, 0, bytes.Length);
260                 memortyStream.Position = 0;
261                 xmlReader = XmlReader.Create(memortyStream);
262                 try
263                 {
264                     ds.ReadXml(xmlReader);
265                 }
266                 finally
267                 {
268                     memortyStream.Close();
269                     xmlReader.Close();
270                 }
271             }
272             catch (Exception ex)
273             {
274                 throw ex;
275             }
276             return ds;
277         }
278
279     }

WebServiceRequest

2、使用

//保存请求
                    Log.WriteLog("查询Request" + requestInfo, "Request", strXml);

                    string xmlHead = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
                                        "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">"
                                           + "<SOAP-ENV:Body>"
                                                + "<m:funMain xmlns:m=\"http://xxxxxxxxxxxxxxxx/\">"
                                                + "<arg0><![CDATA["
                                                + "<businessdata><functioncode>N0004</functioncode>";

                    string xmlEnd = "</businessdata>]]></arg0></m:funMain></SOAP-ENV:Body></SOAP-ENV:Envelope>";
                    strXml = xmlHead + strXml + xmlEnd;

                    WebServiceRequest requestWeb = new WebServiceRequest();
                    requestWeb.Url = SelectHzylCssz("xxxxxx");
                    requestWeb.RequestText = strXml;

                    requestWeb.Start();

                    if (requestWeb.StatusText != null && requestWeb.StatusText != "")
                    {
                        result = "验证失败:" + requestWeb.StatusText;
                        //保存响应内容
                        Log.WriteError("查询发生错误" + requestInfo, "Exception", result);
                        return result;
                    }
                    string resultBody = requestWeb.ResponseText;
                    System.Xml.XmlDocument xmlDocument = new System.Xml.XmlDocument();
                    xmlDocument.LoadXml(resultBody);
                    System.Xml.XmlNode nodes = xmlDocument.SelectSingleNode("//return");
                    xmlDocument.LoadXml(nodes.InnerText);
                    nodes = xmlDocument.SelectSingleNode("//businessdata");
                    //保存响应内容
                    Log.WriteLog("查询Response" + requestInfo, "Response", nodes.InnerXml);

                    if (nodes.SelectSingleNode("//retcode").InnerText.Equals("0"))
                    {
                        result = "0|" + nodes.SelectSingleNode("//bizsequence").InnerText + "|" + nodes.SelectSingleNode("//bizdate").InnerText + "|" + nodes.SelectSingleNode("//prvaccountname").InnerText + "|" + nodes.SelectSingleNode("//prvaccount").InnerText;
                        return result;
                    }

test

3、使用到的一个Log记录类

public class Log
    {
        private static readonly object obj = new object();
        //Response响应
        //Request请求
        /// <summary>
        /// 操作日志
        /// </summary>
        /// <param name="title">标题</param>
        /// <param name="content">日志内容</param>
        public static void WriteLog(string title, string remark, string content)
        {
            WriteLogs(title, remark,content, "操作日志");
        }
        /// <summary>
        /// 错误日志
        /// </summary>
        /// <param name="title">标题</param>
        /// <param name="content">日志内容</param>
        public static void WriteError(string title, string remark, string content)
        {
            WriteLogs(title, remark, content, "错误日志");
        }

        private static void WriteLogs(string title, string remark, string content, string type)
        {
            lock (obj)
            {
                //获取程序基目录
                string path = AppDomain.CurrentDomain.BaseDirectory;

                if (!string.IsNullOrEmpty(path))
                {
                    string st = System.Environment.CurrentDirectory;
                    try
                    {
                        System.Environment.CurrentDirectory = path;
                        System.Environment.CurrentDirectory = "..";
                        path = System.Environment.CurrentDirectory;
                    }
                    finally
                    {
                        System.Environment.CurrentDirectory = st;
                    }
                    try
                    {
                        //获取程序基目录的上一级目录中的自建Log目录
                        path = path + "\\" + "Log";
                        if (!Directory.Exists(path))
                        {
                            Directory.CreateDirectory(path);
                        }

                        path = path + "\\" + DateTime.Now.ToString("yyyy");
                        if (!Directory.Exists(path))
                        {
                            Directory.CreateDirectory(path);
                        }

                        path = path + "\\" + DateTime.Now.ToString("yyyy-MM");
                        if (!Directory.Exists(path))
                        {
                            Directory.CreateDirectory(path);
                        }

                        path = path + "\\" + DateTime.Now.ToString("MM-dd");
                        if (!Directory.Exists(path))
                        {
                            Directory.CreateDirectory(path);
                        }

                        path = path + "\\" + DateTime.Now.Hour.ToString() + ".txt";
                        if (!File.Exists(path))
                        {
                            FileStream fs = File.Create(path);
                            fs.Close();
                        }
                        if (File.Exists(path))
                        {
                            StreamWriter sw = new StreamWriter(path, true, System.Text.Encoding.Default);
                            sw.WriteLine(DateTime.Now + " " + title);
                            sw.WriteLine("日志类型:" + type);
                            sw.WriteLine("备注:" + remark);
                            sw.WriteLine("详情:" + content);
                            sw.WriteLine("----------------------------------------");
                            sw.Close();
                        }
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
            }
        }
        //以下两个方法,用来获取父目录,可设置要获取几级父目录
        //方法一:使用目录函数
        private string get_dir_parent(string dir, int n) //n为几级父目录
        {
            string st = System.Environment.CurrentDirectory;
            try
            {
                System.Environment.CurrentDirectory = dir;

                for (int i = 1; i <= n; i++)
                {

                    System.Environment.CurrentDirectory = "..";

                }
                return System.Environment.CurrentDirectory;
            }
            finally
            {
                System.Environment.CurrentDirectory = st;//恢复最初
            }
        }
        //方法二:使用算法
        private string get_dir_parent1(string dir, int n) //n为几级父目录
        {
            string[] st = dir.Split(‘/‘);

            string rst = st[0];
            if (st.Length - n > 0)
            {
                for (int i = 1; i < st.Length - n; i++)
                {

                    rst += "//" + st[i];

                }
            }
            else
            {
                rst += "//";
            }
            return rst;

        }

    }

Log.cs

时间: 2024-10-20 19:52:14

c# 请求webservice的相关文章

JQuery请求WebService返回数据的几种处理方式

打开自己的博客仔细浏览了一番,发现已经好久没有写博客了,由于最近一直比较忙碌懈怠了好多.默默反省三分钟.......言归正传,现在就对最近在学习webservice的过程中遇到的几种类型的问题中我的理解和解决方案.对于webservice大家肯定知道,它是一种使不同站点之间可以相互通信的技术,可以理解为一种接口.一个站点可以通过其它站点提供的webservice接口获得其它站点提供的相应服务.webservice使用起来非常小巧,轻便被很多站点所使用.对于webservice我不做过多说明,we

jquery ajax跨域请求webservice

有种方式可以通过JSONP方式来请求 这里具体介绍如何通过修改配置文件来实体AJAX跨域请求WEBSERVICE WEBSERVICE的类声名 /// <summary> /// MobileService 的摘要说明 /// </summary> [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)

Node.js 使用 soap 模块请求 WebService 服务接口

项目开发中需要请求webservice服务,前端主要使用node.js 作为运行环境,因此可以使用soap进行请求. 使用SOAP请求webservice服务的流程如下: 1.进入项目目录,安装 soap 模块 > npm install soap --save-dev 2.在项目的 node_modules 目录下找到soap模块下的 lib > client.js, 修改代码: soapAction = ((ns.lastIndexOf("/") !== ns.leng

WebService学习笔记-Ajax请求Webservice

Webservice地址为 http://192.168.13.232:8989/ws_01/umgsai JSP页面地址为 http://192.168.13.232:8080/Demo/index.jsp Webservice的请求体如下 <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:q0="http://ws.umgsai.com/" x

Android 请求WebService 并且解析

直接上代码: 写一个Bean,封装数据 package com.mbl.wbsconn; import java.util.List; import java.util.Map; public class BaseBean { protected String usid; protected String pwd; protected String error; protected String msgtp; protected String logonstatus; protected Lis

jquery ajax跨域请求webservice webconfig配置

jquery ajax跨域请求webservice web.config配置 <configuration> <system.web> <compilation debug="true" targetFramework="4.0" /> <webServices> <protocols> <add name="HttpGet"/> <add name="Htt

.net请求Webservice简单实现天气预报功能

很久没有接触Webservice的知识,今天稍微复习了一下关于webservice,简单做了一个天气预报的功能,虽然界面丑的厉害,但功能算是实现了,以下是效果展示. 这东西没什么难点,只是天气预报的功能在网站类的开发中会经常用到,所以就简单写下,以便以后查阅. 1.新建一个网站或者web应用程序,添加一个aspx页面,用于展示天气数据.(这个应该不用细讲吧) 2.在网上找一个免费的天气预报的接口,我用的是Webxml网站的,地址如下: http://webservice.webxml.com.c

通过HttpClient请求webService

由于服务端是用webService开发的,android要调用webService服务获取数据,这里采用的是通过HttpClient发送post请求,获取webService数据. 服务端使用的webService框架是axis2,请求数据之前,要封装一个xml格式,再通过post请求,获取服务端数据. 请求的xml格式如下所示: 1 <soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope"xmlns:

IOS 使用Http模拟SOAP请求Webservice时内容Unicode编码的实现

IOS上去请求WebService时,为了方便,直接用http POST请求.通过对JAVA版本的抓包发现,请求中的中文字符,都被转成Unicode编码. 如:a被换为 a [其实很简单,获取每个字符的对应的数字,如999,unicode编码即为:ϧ ] 为了实现相关功能,手动将字符串拼接,代码如下: -(NSString *)convert2Unicode:(NSString *)str { NSMutableString *resultString = [[NSMutableString a