无法发送此HttpWebRequest

时间:2012-08-16 12:13:15

标签: c# httpwebrequest

我制作了一个弹出框,其中显示了一个Google验证码,例如:http://www.google.com/sorry/?continue=http://www.google.com/ajax/rd%3Fsky%3Deeuiphp%26ludocid%3D6083833001863340802%26rdu%3DCNzphIbM6rECFWkGtAodP3UAGQ%26sig%3DaY3%26q%3Dtandl%25C3%25A4kare%252Cg%25C3%25B6teborg%2BSweden

然后我在我的程序中输入验证码并将信息发送到下面的下一个函数,它应该将数据提交给Google。我试图用Fiddler跟踪它,但我似乎无法弄清楚出了什么问题。该请求只返回另一个验证码图像。

在Fiddler中,我可以看到当我进入浏览器并提交GET类型的请求时,我将如何向其提交数据?我已经尝试将我的POST切换到GET等等,但总是得到相同的错误,只是另一个验证码图像。

任何想法可能出错?

public string submitGoogleCaptcha(string html, string captchaCode)
    {
        CookieContainer cookieCont = new CookieContainer();

        HttpWebRequest _wReq;
        HttpWebResponse _wResp;
        System.IO.StreamReader _sr;
        System.Text.ASCIIEncoding _enc = new System.Text.ASCIIEncoding();

        string continueValue = Regex.Match(html, @"<input type=""hidden"" name=""continue"" value=""\s*(.+?)\s*"">", RegexOptions.IgnoreCase).Groups[1].Value;
        string idFromGoogle = Regex.Match(html, @"<input type=""hidden"" name=""id"" value=""\s*(.+?)\s*"">", RegexOptions.IgnoreCase).Groups[1].Value;

        string _html = "";
        string postData = "continue=" + continueValue + "&id=" + idFromGoogle + "&captcha=" + captchaCode + "&submit=Submit";

        try
        {
            byte[] _data = _enc.GetBytes(postData);
            _wReq = (HttpWebRequest)WebRequest.Create("http://www.google.com/sorry/Captcha?");


            _wReq.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
            _wReq.Referer = "http://www.google.com/sorry/?continue=" + HttpUtility.UrlEncode(continueValue);
            _wReq.KeepAlive = true;


            _wReq.Method = "POST";
            _wReq.ContentType = "application/x-www-form-urlencoded";
            _wReq.ContentLength = _data.Length;
            _wReq.CookieContainer = cookieCont;
            _wReq.AllowAutoRedirect = true;
            _wReq.UserAgent = "Mozilla/5.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
            System.IO.Stream _outStream = _wReq.GetRequestStream();
            _outStream.Write(_data, 0, _data.Length);
            _outStream.Close();
            _wResp = (HttpWebResponse)_wReq.GetResponse();
            _sr = new System.IO.StreamReader(_wResp.GetResponseStream());
            _html = _sr.ReadToEnd();
            _sr.Close();
            _wResp.Close();
        }
        catch (Exception ee)
        {

        }


        return _html;
    }

1 个答案:

答案 0 :(得分:0)

当我尝试您发布的代码时,您会遇到异常。你知道如果你没有用catch(Exception ee){}隐藏自己的所有例外情况。您得到的例外是试图告诉您服务器发回503错误“服务器不可用”。

我建议您学习一些基本的异常处理原则。

另外,我在Fiddler看到了请求。