HttpWebRequest.GetResponse连续失败,直到程序重置

时间:2011-09-28 17:31:55

标签: c#

有时在某些计算机上,Web请求将失败并显示以下消息,并继续执行此操作,直到程序重置为止,此时它将再次开始工作。有没有其他人经历过这一点,是否有任何程序化的方法来防止它?

Message: The remote name could not be resolved: 'www.validwebsite.com' Source: System StackTrace: at System.Net.HttpWebRequest.GetResponse()

编辑:这是正在执行的代码

    virtual public string Execute(string web_uri,string request_method,string data = null, string content_type = null)
    {
        WebRequest webRequest = WebRequest.Create(web_uri);
        webRequest.Method = request_method;
        if (content_type != null)
        {
            webRequest.ContentType = content_type;
        }
        webRequest.Method = request_method;
        byte[] bytes = new byte[0];
        if (!string.IsNullOrEmpty(data))
        {
            bytes = Encoding.ASCII.GetBytes(data);
            // send the Post
            webRequest.ContentLength = bytes.Length;   //Count bytes to send
        }
        else
        {
            webRequest.ContentLength = 0;
        }
        if (webRequest.Method == "POST")
        {
            using (Stream os = webRequest.GetRequestStream())
            {
                os.Write(bytes, 0, bytes.Length);         //Send it
            }
        }
        using (HttpWebResponse webResponse =(HttpWebResponse)webRequest.GetResponse())
        {
            if (webResponse != null)
            {
                ResponseCode = webResponse.StatusCode;
                using (StreamReader sr = new StreamReader(webResponse.GetResponseStream(),Encoding.UTF8))
                {
                    string xml_string = sr.ReadToEnd().Trim();
                    return xml_string;
                }
            }
        }
        return null;

1 个答案:

答案 0 :(得分:1)

在hosts文件中输入一个条目以排除DNS问题。如果你的应用程序然后一致地工作,你就发现了问题。