当前位置:编程学习 > C#/ASP.NET >>

C#带cookie访问网页 返回有时为空

if (string.IsNullOrEmpty(param_URL))
            {
                return null;
            }
            //设置编码方式
            Encoding localEncoding = Encoding.Default;
            string local_SourceCode = string.Empty;
            //如果自定义编码方式为空,就用默认编码方式
            if (!string.IsNullOrEmpty(param_Encoding))
            {
                localEncoding = Encoding.GetEncoding(param_Encoding);
            }

            //创建请求实例
            HttpWebRequest localWebRequest = HttpWebRequest.Create(param_URL) as HttpWebRequest;
            localWebRequest.UserAgent = "Mozilla/5.0 (Windows NT 5.2; rv:5.0) Gecko/20100101 Firefox/5.0";
            localWebRequest.Timeout = 10000;//设置超时10秒,然后报异常
            localWebRequest.Headers.Add(HttpRequestHeader.Cookie, param_CookieInfo);
            //localWebRequest.Host = "product.dangdang.com";
            //localWebRequest.Accept = "*/*";
            
            if (param_CookieContainer != null)
            {
                localWebRequest.CookieContainer = param_CookieContainer;
            }

            if (param_RefererRUL != null)
            {
                localWebRequest.Referer = param_RefererRUL;
            }

            //创建响应实例
            HttpWebResponse localWebResponse = null;
            //以指定的字符集从流中读取字符
            StreamReader localStrramReader = null;
            try
            {
                localWebResponse = localWebRequest.GetResponse() as HttpWebResponse;
                //以指定的字符集从流中读取字符
                localStrramReader = new StreamReader(localWebResponse.GetResponseStream(), localEncoding);

                local_SourceCode = localStrramReader.ReadToEnd();
            }
            catch (Exception ex)
            {
                local_SourceCode = string.Empty;
                //SimpleLog.WriteLog("WebStreamerUtility", "GetWebStreamByURLAndEncodint", "Error:" + ex.Message);
            }
            finally
            {
                if (null != localWebResponse)
                {
                    localWebResponse.Close();
                }
                if (null != localStrramReader)
                {
                    localStrramReader.Close();
                }
            }

            //将从网页流中读取的字符返回
            return local_SourceCode;



有时候返回为空 有时候可以返回 原因出在哪呢 哪位大侠帮助找下原因
补充:.NET技术 ,  C#
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,