【问题标题】:How do I perform a simple GET request with cookies in C#如何在 C# 中使用 cookie 执行简单的 GET 请求
【发布时间】:2018-08-28 02:53:23
【问题描述】:

我发现的一切要么是关于 POST 请求,要么是不假设 cookie。

我有一个这样的网址:

http://page.com/find/1,1,1,find.html?advanced=1&param1=val1&param2[]=val2

当放入浏览器时,这会将我引导至搜索结果页面。现在我想在 C# 程序中复制它。到目前为止我有这个:

WebRequest req = WebRequest.Create(url);
((HttpWebRequest)req).UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:10.0.2) Gecko/20100101 Firefox/10.0.2";
req.Method = "GET";
WebResponse response = req.GetResponse();

当我运行它时,它会按预期返回“请登录”页面。但是其中一个参数有问题。这是响应网址:

http://page.com/login.html?ref=find/1,1,1,find.html?advanced=1&param1=val1&param2=Array

那么,有两个问题:param2 可能发生了什么?以及如何向其中添加 cookie?

编辑:通过强制转换为 HttpWebRequest 来设置 cookie。

【问题讨论】:

    标签: c# http cookies network-programming get


    【解决方案1】:

    正如 devio 所说,您应该使用 HttpWebRequest。我做了肮脏的测试来检查它。

    准备要发送的 cookie。我为整个 localhost 提供了:

    HttpWebRequest rq = (HttpWebRequest)WebRequest.Create("http://localhost/test.php");
    rq.CookieContainer = new CookieContainer();
    rq.CookieContainer.Add(new Cookie("test", "xxxx", "/", "localhost"));
    

    您的脚本应设置 cookie 以使其在响应中可用。你可以使用它们。

    HttpWebResponse resp = (HttpWebResponse)rq.GetResponse();
    foreach(var c in resp.Cookies)
    {
        Debug("{0}: {1}", c.Name, c.Value);
    }
    

    【讨论】:

      【解决方案2】:

      你可以使用这段代码:

      Cookie SessionCookie = new Cookie("{CookieName}", {Cookievalue})
      {
          Domain = "{domain you want to hit}", Path = "/", Expired = false, HttpOnly = true 
      };
      
      CookieContainer SessionCookieHolder = new CookieContainer();
      
      SessionCookie.Add(SessionCookie);
      
      try
      {
         HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create("{URL}");
         WebReq.CookieContainer = SessionCookie;
         WebReq.Method = "GET/POST/HEAD"; //depending on the request type//
         WebReq.KeepAlive = true;
         HttpWebResponse Resp = (HttpWebResponse)WebReq.GetResponse();
      }
      
      catch(Exception ex)
      
      {
         string ExceptionReader = ex.Message;
      }
      

      【讨论】:

      • 您好,欢迎来到 stackoverflow。尽管此代码可能有效,但此处对带有解释的答案的重视程度要高得多。您能否请edit您的答案并添加一些解释代码以及它如何解决问题的散文?这样一来,其他人就可以从中更好地学习,而不仅仅是从网上复制和粘贴一些东西。
      【解决方案3】:

      Cookie 存储在 HttpWebRequest.CookieContainerHttpWebResponse.Cookies 属性中。

      对于后续请求,您需要将响应的 cookie 添加到请求的 cookie 容器中。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-04-14
        • 2021-09-28
        • 1970-01-01
        • 2016-07-04
        • 2016-11-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多