Multiple WebRequest in same session

后端 未结 1 409
予麋鹿
予麋鹿 2020-12-06 05:13

I am trying to write a function which saves a webpage (with its images) as a html page. I am using HttpWebRequest to request for the content of webpages. My function looks s

相关标签:
1条回答
  • 2020-12-06 05:40

    Sessions generally work by using cookies. If you want all your requests to be part of the same session, you need to persist the cookies between requests. You do this by creating a CookieContainer and providing it to each of the HttpWebRequest objects.

    Here's your code updated to use a CookieContainer:

        void SaveUrl(string sourceURL, string savepath) {
            CookieContainer cookies = new CookieContainer();
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(sourceURL);
            webRequest.CookieContainer = cookies;
    
            HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
            StreamReader responseReader = new StreamReader(response.GetResponseStream());
    
            string sResponseHTML = responseReader.ReadToEnd();
            using (StreamWriter sw = new StreamWriter(savepath, false)) {
                sw.Write(sResponseHTML);
            }
    
            string[] ImageUrl = GetImgLinks(sResponseHTML);
            foreach (string imagelink in ImageUrl) {
                HttpWebRequest imgRequest = (HttpWebRequest)WebRequest.Create(imagelink);
                imgRequest.CookieContainer = cookies;
                HttpWebResponse imgresponse = (HttpWebResponse)imgRequest.GetResponse();
                //Code to save image
            }
        }
    
    0 讨论(0)
提交回复
热议问题