c# - 通过 C# 模拟请求时出现错误 Forbidden 403

标签 c# httpwebrequest

范围:

我正在开发一个 C# 应用程序来模拟对 this site 的查询。我非常熟悉模拟 Web 请求以实现相同的人工步骤,但使用代码代替。

如果您想亲自尝试,只需在 CNPJ 框中输入此号码即可: 08775724000119 并输入验证码并单击Confirmar

我已经处理了验证码,所以这不再是问题了。

问题:

一旦我执行“CNPJ”的 POST 请求,就会抛出异常:

The remote server returned an error: (403) Forbidden.

Fiddler 调试器输出:

Link for Fiddler Download

这是我的浏览器生成的请求,而不是我的代码

POST https://www.sefaz.rr.gov.br/sintegra/servlet/hwsintco HTTP/1.1
Host: www.sefaz.rr.gov.br
Connection: keep-alive
Content-Length: 208
Cache-Control: max-age=0
Origin: https://www.sefaz.rr.gov.br
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko)    Chrome/23.0.1271.97 Safari/537.11
Content-Type: application/x-www-form-urlencoded
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Referer: https://www.sefaz.rr.gov.br/sintegra/servlet/hwsintco
Accept-Encoding: gzip,deflate,sdch
Accept-Language: pt-BR,pt;q=0.8,en-US;q=0.6,en;q=0.4
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
Cookie: GX_SESSION_ID=gGUYxyut5XRAijm0Fx9ou7WnXbVGuUYoYTIKtnDydVM%3D;   JSESSIONID=OVuuMFCgQv9k2b3fGyHjSZ9a.undefined


//    PostData : 
_EventName=E%27CONFIRMAR%27.&_EventGridId=&_EventRowId=&_MSG=&_CONINSEST=&_CONINSESTG=08775724000119&cfield=rice&_VALIDATIONRESULT=1&BUTTON1=Confirmar&sCallerURL=http%3A%2F%2Fwww.sintegra.gov.br%2Fnew_bv.html

使用的代码示例和引用:

我正在使用自己开发的库来处理/包装 Post 和 Get 请求。

请求对象具有与浏览器发出的参数相同的参数(Host、Origin、Referer、Cookies..)(在此处记录了我的 fiddler)。

我还设法使用以下方法设置证书的 ServicePointValidator:

ServicePointManager.ServerCertificateValidationCallback = 
    new RemoteCertificateValidationCallback (delegate { return true; });

完成所有配置后,我仍然遇到禁止的异常。

这是我如何模拟请求并抛出异常

        try
        {
            this.Referer = Consts.REFERER;

            // PARAMETERS: URL, POST DATA, ThrownException (bool)
            response = Post (Consts.QUERYURL, postData, true);
        }
        catch (Exception ex)
        {
            string s = ex.Message;
        }

提前感谢您对我的问题的任何帮助/解决方案

更新1:

我错过了生成 cookie 的主页请求(感谢 @W0lf 指出这一点)

现在还有另一件奇怪的事情。 Fiddler 没有在请求中显示我的 Cookie,但它们在这里: CookieJar

最佳答案

我使用浏览器发出了成功的请求,并将其记录在Fiddler中。

与您的要求唯一不同的是:

  • 我的浏览器没有发送 sCallerURL 参数的值(我有 sCallerURL= 而不是 sCallerURL=http%3A%2F%2Fwww...)
  • session ID 不同(显然)
  • 我还有其他 Accept-Language: 值(我很确定这并不重要)
  • Content-Length 不同(显然)

更新

好吧,我以为 Fiddler 跟踪来自您的应用程序。如果您没有根据您的请求设置 cookie,请执行以下操作:

  • 在发布数据之前,请向 https://www.sefaz.rr.gov.br/sintegra/servlet/hwsintco 发出 GET 请求。如果您检查响应,您会发现网站发送了两个 session Cookie。
  • 当您执行 POST 请求时,请务必附加您在上一步中获取的 Cookie

如果您不知道如何存储 cookie 并在其他请求中使用它们,请查看 here .

更新2

问题

好的,我成功地重现了 403,找出了导致它的原因,并找到了修复方法。

POST 请求中发生的情况是:

  • 服务器响应状态 302(临时重定向)和重定向位置
  • 浏览器重定向(基本上是执行 GET 请求)到该位置,同时发布两个 Cookie。

.NET 的 HttpWebRequest 尝试无缝地执行此重定向,但在这种情况下存在两个问题(我会考虑 .NET 实现中的错误):

  1. POST(重定向)后的 GET 请求与 POST 请求具有相同的内容类型 (application/x-www-form-urlencoded)。对于 GET 请求,不应指定此值

  2. Cookie 处理问题(最重要的问题) - 网站发送两个 Cookie:GX_SESSION_IDJSESSIONID。第二个指定了路径 (/sintegra),而第一个则没有。

区别在于:浏览器默认为第一个 cookie 分配 /(root) 路径,而 .NET 为其分配请求 url 路径 (/sintegra/servlet/hwsintco )。

因此,最后一个 GET 请求(重定向后)到 /sintegra/servlet/hwsintpe... 不会获取传入的第一个 cookie,因为它的路径不对应。​​

修复

  • 对于重定向问题(使用内容类型的 GET),解决方法是手动执行重定向,而不是依赖 .NET 来实现此目的。

为此,请告诉它不要遵循重定向:

postRequest.AllowAutoRedirect = false

然后从 POST 响应中读取重定向位置并手动对其执行 GET 请求。

为此,我发现的修复方法是从 CookieContainer 中取出放错位置的 cookie,正确设置其路径并将其添加回容器中的正确位置。

这是执行此操作的代码:

private void FixMisplacedCookie(CookieContainer cookieContainer)
{
    var misplacedCookie = cookieContainer.GetCookies(new Uri(Url))[0];

    misplacedCookie.Path = "/"; // instead of "/sintegra/servlet/hwsintco"

    //place the cookie in thee right place...
    cookieContainer.SetCookies(
        new Uri("https://www.sefaz.rr.gov.br/"), 
        misplacedCookie.ToString());
}
<小时/>

以下是使其工作的所有代码:

using System;
using System.IO;
using System.Net;
using System.Text;

namespace XYZ
{
    public class Crawler
    {

        const string Url = "https://www.sefaz.rr.gov.br/sintegra/servlet/hwsintco";

        public void Crawl()
        {
            var cookieContainer = new CookieContainer();

            /* initial GET Request */
            var getRequest = (HttpWebRequest)WebRequest.Create(Url);
            getRequest.CookieContainer = cookieContainer;
            ReadResponse(getRequest); // nothing to do with this, because captcha is f#@%ing dumb :)

            /* POST Request */
            var postRequest = (HttpWebRequest)WebRequest.Create(Url);

            postRequest.AllowAutoRedirect = false; // we'll do the redirect manually; .NET does it badly
            postRequest.CookieContainer = cookieContainer;
            postRequest.Method = "POST";
            postRequest.ContentType = "application/x-www-form-urlencoded";

            var postParameters =
                "_EventName=E%27CONFIRMAR%27.&_EventGridId=&_EventRowId=&_MSG=&_CONINSEST=&" +
                "_CONINSESTG=08775724000119&cfield=much&_VALIDATIONRESULT=1&BUTTON1=Confirmar&" +
                "sCallerURL=";

            var bytes = Encoding.UTF8.GetBytes(postParameters);

            postRequest.ContentLength = bytes.Length;

            using (var requestStream = postRequest.GetRequestStream())
                requestStream.Write(bytes, 0, bytes.Length);

            var webResponse = postRequest.GetResponse();

            ReadResponse(postRequest); // not interested in this either

            var redirectLocation = webResponse.Headers[HttpResponseHeader.Location];

            var finalGetRequest = (HttpWebRequest)WebRequest.Create(redirectLocation);


            /* Apply fix for the cookie */
            FixMisplacedCookie(cookieContainer);

            /* do the final request using the correct cookies. */
            finalGetRequest.CookieContainer = cookieContainer;

            var responseText = ReadResponse(finalGetRequest);

            Console.WriteLine(responseText); // Hooray!
        }

        private static string ReadResponse(HttpWebRequest getRequest)
        {
            using (var responseStream = getRequest.GetResponse().GetResponseStream())
            using (var sr = new StreamReader(responseStream, Encoding.UTF8))
            {
                return sr.ReadToEnd();
            }
        }

        private void FixMisplacedCookie(CookieContainer cookieContainer)
        {
            var misplacedCookie = cookieContainer.GetCookies(new Uri(Url))[0];

            misplacedCookie.Path = "/"; // instead of "/sintegra/servlet/hwsintco"

            //place the cookie in thee right place...
            cookieContainer.SetCookies(
                new Uri("https://www.sefaz.rr.gov.br/"),
                misplacedCookie.ToString());
        }
    }
}

关于c# - 通过 C# 模拟请求时出现错误 Forbidden 403,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14139707/

相关文章:

.net - HttpWebRequest - POST 中不允许使用括号

C# 如何处理 "check on"、 "cancel"并等待异步 Web 请求?

ssl - Silverlight 2.0 中 SLL Uri 的 HttpWebRequest

c# - 如何检查 csproj 中的条件编译符号

C# - 套接字未接收所有字节

c# - 无法处理从 HTTP/HTTPS 协议(protocol)到其他不同协议(protocol)的重定向

c# - 如何为单元测试填充 HttpWebResponse.GetResponseAsync()?

c# - 如何在从 Visual Studio 运行的 Web 服务中记录输出

c# - 从代码调用时Mysql存储过程结果不同

c# - LINQ2SQL 选择订单并跳过/接受