码迷,mamicode.com
首页 > Web开发 > 详细

HttpWebRequest 基础连接已经关闭: 接收时发生错误

时间:2015-02-02 17:31:33      阅读:2893      评论:0      收藏:0      [点我收藏+]

标签:

技术分享
HttpWebRequest request = null;
            Stream webStream = null;
            HttpWebResponse response = null;
            StreamReader reader = null;
            string responseString = "";

            try
            {
                byte[] bf = Encoding.UTF8.GetBytes(postString);
                request = WebRequest.Create(url) as HttpWebRequest;
                request.Method = "POST";
                request.ServicePoint.Expect100Continue = false;
                request.Timeout = 1000 * 3;
                request.ContentType = "application/x-www-form-urlencoded";
                request.KeepAlive = false;
                request.ProtocolVersion = HttpVersion.Version11;  
                request.ContentLength = bf.Length;
                webStream = request.GetRequestStream();
                webStream.Write(bf, 0, bf.Length);

                response = (HttpWebResponse)request.GetResponse();
                reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);

                responseString = reader.ReadToEnd();

                Log.Info(responseString);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                request.Abort();
                request = null;
                if (webStream != null)
                {
                    webStream.Close();
                }
                if (reader != null)
                {
                    reader.Close();
                }
                if (response != null)
                {
                    response.Close();
                    response = null;
                }
            }

            

            //解析
            JavaScriptSerializer jsonConvert = new JavaScriptSerializer();
            dynamic responseObj = jsonConvert.DeserializeObject(responseString);
            if (responseObj is Dictionary<string, object>)
            {
                Dictionary<string, object> jsonobj = (Dictionary<string, object>)responseObj;
                message.ResponseMessage = string.Format("[{0}]"+jsonobj["ResultDesc"].ToString(),DateTime.Now.ToString());
            }
View Code

 

在调试短信通信接口的时候出现 “基础连接已经关闭: 接收时发生错误”

研究很长时间 ,没找到原因,查找网上解决方案,其中一位仁兄的方案提供了帮助,这里友情连接一下:http://blog.csdn.net/liehuo123/article/details/7071636

 

总结一下原因,可能是必须指定双方http协议相同。

网上还有其他的解决方案,如

MyRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)";

这个没试过。

诸君如果以上方式不能解决,请请教百度君。

HttpWebRequest 基础连接已经关闭: 接收时发生错误

标签:

原文地址:http://www.cnblogs.com/LL-723/p/4268020.html

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