如何为登录表单后面的 WebClient.downloadstring 设置身份验证 cookie

时间:2021-03-11 08:31:02

标签: c# cookies webclient downloadstring

我正在尝试使用 WebClient.DownloadString() 从 URL 中抓取 JSON 数据。

问题是我发现以编程方式访问 URL:“secure.somesite.com.au/api/products/getprice?productName=Cornmeal” 导致站点强行关闭连接。 我相信这是因为未设置身份验证 cookie。

如何设置cookie?我花了一些时间阅读 stackoverflow 和 codeproject,但没有人设置实际的 cookie,他们都在设置用户名和密码。我需要设置 cookie,以便网站知道我应该有权访问。

 using (var client = new CookieAwareWebClient())
        {
            Cookie cookie = new Cookie();
            cookie.Name = "SWI";
            cookie.Value = "kjuujj7kxPvEC-4fBt5yyzWOJnjhriuoOtZ6Z0Ww";
            cookie.Domain = ".secure.somesite.com.au";
            client.CookieContainer.Add(cookie);

            string r = client.DownloadString("https://secure.somesite.com.au/api/products/getprice?productName=Cornmeal");
        }

CookieAwareWebClient 类:

public class CookieAwareWebClient : WebClient
    {
        public CookieAwareWebClient()
        {
            CookieContainer = new CookieContainer();
        }
        public CookieContainer CookieContainer { get; private set; }

        protected override WebRequest GetWebRequest(Uri address)
        {
            var request = (HttpWebRequest)base.GetWebRequest(address);
            request.CookieContainer = CookieContainer;
            return request;
        }
    }

附注。我试图用 WebClient 登录,但我得到的只是连接被强行关闭。我认为这是因为如果您尚未登录,则请求受保护的资源会导致 WebClient 中出现错误,而不仅仅是返回一个字符串“null”或其他内容。

PPS。我已经在 python 中完成了这个,但现在需要它在 C# 中工作。

  client.get('https://secure.somesite.com.au/api/products/getprice', params={
                'productCode': '{}'.format(code)
            }, headers=headers, timeout=60)

此处的 cookie 位于标题中。

0 个答案:

没有答案
相关问题