相关疑难解决方法(0)

将CookieContainer与WebClient类一起使用

我之前使用过带有HttpWebRequest和HttpWebResponse会话的CookieContainer,但现在,我想将它与WebClient一起使用.据我所知,没有像HttpWebRequests(request.CookieContainer)那样的内置方法.如何从CookieContainer中的WebClient收集cookie?

我用Google搜索并找到以下示例:

public class CookieAwareWebClient : WebClient
{
    private readonly CookieContainer m_container = new CookieContainer();

    protected override WebRequest GetWebRequest(Uri address)
    {
        WebRequest request = base.GetWebRequest(address);
        HttpWebRequest webRequest = request as HttpWebRequest;
        if (webRequest != null)
        {
            webRequest.CookieContainer = m_container;
        }
        return request;
    }
}
Run Code Online (Sandbox Code Playgroud)

这是最好的方法吗?

c# cookies webclient httpwebrequest cookiecontainer

142
推荐指数
5
解决办法
13万
查看次数

错误禁止403通过C#模拟请求

范围:

我正在开发一个C#aplication来模拟对这个站点的查询.我非常熟悉模拟Web请求以实现相同的人工步骤,但使用代码.

如果您想尝试自己,只需在CNPJ框中键入此编号: 08775724000119然后编写验证码并单击Confirmar

我已经使用验证码了,所以这不再是问题了.

问题:

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

远程服务器返回错误:(403)禁止.

Fiddler调试器输出:

链接Fiddler下载

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

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
Run Code Online (Sandbox Code Playgroud)

使用的代码示例和参考:

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

请求对象具有与浏览器发出的参数(Host,Origin,Referer,Cookies ..)相同的参数(在此处记录我的提琴手).

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

ServicePointManager.ServerCertificateValidationCallback = 
    new RemoteCertificateValidationCallback (delegate { return true; });
Run Code Online (Sandbox Code Playgroud)

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

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

        try
        {
            this.Referer …
Run Code Online (Sandbox Code Playgroud)

c# httpwebrequest

2
推荐指数
1
解决办法
1万
查看次数

标签 统计

c# ×2

httpwebrequest ×2

cookiecontainer ×1

cookies ×1

webclient ×1