HttpWebRequest pass credentials to next HttpWebRequest

前端 未结 3 1442
执笔经年
执笔经年 2020-12-17 06:55

I am logging into a page using HttpWebRequest and getting some information. I then use that information to create a new HttpWebRequest to get some more information. I do not

3条回答
  •  悲&欢浪女
    2020-12-17 06:59

    This is a really old question and I know it states no WebClient but I will post here for everyone who comes across this from Google. The original concept is not my code. I do not know where I originally found it.

    using (WebClientEx client = new WebClientEx())
    {
      client.IntTimeout = intTimeout;
      client.DownloadString(strReportUrlPrefix + strReportUrlQuery);
    
      NameValueCollection auth = new NameValueCollection
      {
        { "j_username", strReportUsername},
        { "j_password", strReportPassword}
      };
    
      byte[] data = client.UploadValues(strReportUrlPrefix + "j_security_check", auth);
    
      // LOGIC HERE WITH DATA
    }
    

    WebClientEx Class:

    public class WebClientEx : WebClient
    {
      private CookieContainer _cookieContainer = new CookieContainer();
      public int IntTimeout { get; set; }
    
      protected override WebRequest GetWebRequest(Uri address)
      {
        WebRequest request = base.GetWebRequest(address);
        if (request != null)
          request.Timeout = IntTimeout;
    
        if (request is HttpWebRequest)
          (request as HttpWebRequest).CookieContainer = _cookieContainer;
    
        return request;
      }
    }
    

提交回复
热议问题