码迷,mamicode.com
首页 > Windows程序 > 详细

c# 请求webservice

时间:2016-04-12 15:51:56      阅读:433      评论:0      收藏:0      [点我收藏+]

标签:

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

 

c# 请求webservice

标签:

原文地址:http://www.cnblogs.com/zzfon/p/5382850.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!