URL在浏览器中工作,但不能从Web客户端或Web请求获得响应

时间:2013-01-17 06:39:36

标签: c# winforms httpwebrequest webrequest webresponse

我遇到有关服务器响应的问题。 (返回403禁止)。

当我在浏览器中检查相同的URL时,我可以看到该页面。

我已经编写了以下代码来获得回复。

相同的代码我在我的本地PC上执行,它工作正常。

 HttpWebRequest request = WebRequest.Create(RequestUrl) as HttpWebRequest;
                request.Method = "POST";
                request.CookieContainer = new CookieContainer();
                request.Timeout = 600000;
                request.Accept = "*/*";
                request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; rv:18.0) Gecko/20100101 Firefox/18.0";

WebResponse response;
                try
                {
                    response = request.GetResponse();
                    string StatusDescription = ((HttpWebResponse)response).StatusDescription;

                    if (StatusDescription.ToLower() == "ok")
                    {
                        Stream dataStream = response.GetResponseStream();
                        //XmlDocument XmlResponse = new XmlDocument();
                        //XmlResponse.Load(dataStream);            
                        //XmlResponse.Save(Server.MapPath("~/XMLResponse.xml"));
                        StreamReader reader = new StreamReader(dataStream);
                        string responseFromServer = reader.ReadToEnd();
                        responseFromServer = responseFromServer.Replace(" ", "");
                        responseFromServer = responseFromServer.Replace("&", "&");
                        reader.Close();
                        dataStream.Dispose();
                        response.Close();
                        responseFromServer = GetStringsBetweenTags(responseFromServer, "<head>", "</head>");
                        return responseFromServer;
                    }
                    else
                    {
                        //To Do : add code for notify error via email
                    }
                }
                catch (Exception ex)
                {                   
                    WebClient webclient = new WebClient();
                    using (StreamReader reader = new StreamReader(webclient.OpenRead(RequestUrl)))
                    {
                        string responseFromServer = reader.ReadToEnd();
                        responseFromServer = responseFromServer.Replace("&nbsp;", "");
                        responseFromServer = responseFromServer.Replace("&", "&amp;");
                        reader.Close();
                        webclient.Dispose();
                        responseFromServer = GetStringsBetweenTags(responseFromServer, "<head>", "</head>");
                        return responseFromServer;

                    }

                }

1 个答案:

答案 0 :(得分:4)

下载Fiddler(http://www.fiddler2.com/fiddler2/)

然后导航到URL并查看标题。然后查看应用程序发送的标头。您 POSTING 的网址明显阻止了某些请求。