关于webResponse类使用的时候超时问题

2025-05-18 19:27:25
推荐回答(3个)
回答1:

把我封装的方法给你吧:

    static string GetPage(string url, string param, string proxy, string method)
    {
        if (method != "POST" && !string.IsNullOrEmpty(param)){
            if(url.IndexOf('?') > 0)
                url += "&" + param;
            else
                url += "?" + param;
        }
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.Headers.Add(HttpRequestHeader.CacheControl, "no-cache");
        request.Headers.Add("Accept-Charset", "utf-8");
        request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0;)";
        request.AllowAutoRedirect = true; //出现301或302之类的转向时,是否要转向
        if (!string.IsNullOrEmpty(proxy))
        {
            string[] tmp = proxy.Split(new[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
            int port = 80;
            if (tmp.Length >= 2)
                if (!int.TryParse(tmp[1], out port))
                    port = 80;
            request.Proxy = new WebProxy(tmp[0], port);
        }
        request.Method = method;//"GET";//"POST";
        request.ContentType = "application/x-www-form-urlencoded";
        // 设置提交的数据
        if (method == "POST" && !string.IsNullOrEmpty(param))
        {
            // 把数据转换为字节数组
            byte[] l_data = Encoding.UTF8.GetBytes(param);
            request.ContentLength = l_data.Length;
            // 必须先设置ContentLength,才能打开GetRequestStream
            // ContentLength设置后,reqStream.Close前必须写入相同字节的数据,否则Request会被取消
            using (Stream newStream = request.GetRequestStream())
            {
                newStream.Write(l_data, 0, l_data.Length);
                newStream.Close();
            }
        }
        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        using (Stream stream = response.GetResponseStream())
        {
            using (var sr = new StreamReader(stream, Encoding.UTF8))
            {
                return sr.ReadToEnd();
            }
        }
    }

回答2:

试试设置ConentLength

回答3:

你 判断你访问的网址手动访问下是不是可以访问?