reCaptcha和.NET的问题

时间:2010-05-26 09:49:01

标签: .net post httpwebrequest recaptcha

我在reCaptcha中遇到了这个错误:

'Input error: response: Required field must not be blank
challenge: Required field must not be blank
privatekey: Required field must not be blank'

我正在通过POST发送数据,所以我不明白发生了什么。这是我使用的代码:

    public static Boolean Check(String challenge, String response)
    {
        try
        {
            String privatekey = "7LeAbLoSAAAABJBn05uo6sZoFNoFnK2XKyF3dRXL";
            String remoteip = HttpContext.Current.Request.UserHostAddress;

            WebRequest req = WebRequest.Create("http://api-verify.recaptcha.net/verify");
            req.Method = "POST";

            using (StreamWriter sw = new StreamWriter(req.GetRequestStream()))
            {
                sw.Write("privatekey={0}&remoteip={1}&challenge={2}&response={3}", privatekey, remoteip, challenge, response);
                sw.Flush();
            }

            String resultString = String.Empty;
            String errorString = String.Empty;
            using (StreamReader sr = new StreamReader(req.GetResponse().GetResponseStream()))
            {
                resultString = sr.ReadLine();
                errorString = sr.ReadLine();
            }

            Boolean b;
            return Boolean.TryParse(resultString, out b) && b;
        }
        catch (Exception)
        {
            return false;
        }
    }

(当然,这不是正确的私钥:P)

我不知道问题是什么,我认为我正确地发送了数据,但是这个错误显示我显然没有发送任何内容。

可能是什么问题?

干杯。

1 个答案:

答案 0 :(得分:1)

很好,我忘记了如何正确地进行发布¬¬'

public static Boolean Check(String challenge, String response)
{
    try
    {
        String privatekey = "7LeAbLoSAAAABJBn05uo6sZoFNoFnK2XKyF3dRXL";
        String remoteip = HttpContext.Current.Request.UserHostAddress;

        WebRequest req = WebRequest.Create("http://api-verify.recaptcha.net/verify");
        req.Method = "POST";

        byte[] byteArray = Encoding.UTF8.GetBytes(String.Format("privatekey={0}&remoteip={1}&challenge={2}&response={3}", privatekey, remoteip, challenge, response));
        req.ContentType = "application/x-www-form-urlencoded";
        req.ContentLength = byteArray.Length;

        req.GetRequestStream().Write(byteArray, 0, byteArray.Length);

        String resultString = String.Empty;
        String errorString = String.Empty;
        using (StreamReader sr = new StreamReader(req.GetResponse().GetResponseStream()))
        {
            resultString = sr.ReadLine();
            errorString = sr.ReadLine();
        }

        Boolean b;
        return Boolean.TryParse(resultString, out b) && b;
    }
    catch (Exception)
    {
        return false;
    }
}

现在正在运作。