.NET 后台提交POST请求


.NET 后台提交POST请求

请看下面的一个小示例

 public OperationResult GetRequestResult(string Command, Dictionary<string, string> Params)
        {
            try
            {
                //建立http请求
                HttpWebRequest hrq = (HttpWebRequest)WebRequest.Create("这里是URL");
                // hrq.Credentials = CredentialCache.DefaultCredentials;
                hrq.Proxy = WebRequest.GetSystemWebProxy();
                hrq.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore); ;
                hrq.Method = "post";
                hrq.CookieContainer = new CookieContainer();

                using (Stream strm = hrq.GetRequestStream())
                {//写入请求数据流
                    XmlWriterSettings ws = new XmlWriterSettings();
                    ws.Encoding = Encoding.UTF8;
                    using (XmlWriter xw = XmlWriter.Create(strm, ws))
                    {
                        xw.WriteStartElement("message");
                        xw.WriteStartElement("head");
                        WriteValue(xw, "version", "1.0");
                          WriteValue(xw, "loginemail", "1@1.com");
                        xw.WriteEndElement();
                        xw.WriteStartElement("body");
                        xw.WriteEndElement();
                        xw.WriteEndElement();
                        xw.Flush();
                    }
                }

                WebResponse resp = hrq.GetResponse();

                string ErrorId = string.Empty;
                string Mesaage = string.Empty;
                using (Stream strm = resp.GetResponseStream())
                {

                    XmlDocument doc = new XmlDocument();
                    doc.Load(strm);
                    XmlNode root = doc.DocumentElement;
                    XmlNode code = root.SelectSingleNode("/message/head/field[@name='RESP_CODE']");
                    XmlNode msg = root.SelectSingleNode("/message/head/field[@name='RESP_MSG']");
                    if ((msg != null) && (code != null))
                    {
                        ErrorId = code.InnerText;
                        Mesaage = msg.InnerText;
                        int r = 0;
                        if ((!int.TryParse(ErrorId, out r)) || (r != 0))
                        {
                            return OperationResult.CreateResult(-2, Mesaage);
                        }
                    }
                    return OperationResult.CreateResult(0, string.Empty, doc.OuterXml);
                }
            }
            catch (Exception e)
            {
                if (e is WebException)
                {
                    switch (((WebException)e).Status)
                    {
                        case WebExceptionStatus.ConnectFailure:
                        case WebExceptionStatus.Timeout:
                            return OperationResult.CreateResult(-1, "由于连接不上服务器,故暂时无法操作,请耐心等候。");
                    }
                }
                return OperationResult.CreateResult(-1, e.Message);
            }
            finally
            {
            }
        }

上面这段代码了就是最简单直接的请求 通过XML 传输数据

数据模型转换成XML 获取请求地址的返回数据 前后台进行相应的解析就可以了 相对于来说比较传统

还有一种是比较方便的 用自带的 System.Net 的 WebClient

    public void RequestWeb(object msg)
        {
            WebClient client = new WebClient();
            client.UploadStringAsync(new Uri("http://localhost:1234/handler1.ashx"), "");
            client.UploadStringCompleted += client_UploadStringCompleted;
        }

        void client_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            WriteInLog(e.Result);
        }

 这个组件还是比较方便的包含了大多数需要的方法包括Async线程等等 网上的资料很多

原文地址:https://www.cnblogs.com/dinghuijun/p/2735421.html