C# 同一会话中的多个 WebRequest
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/787857/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Multiple WebRequest in same session
提问by Ankit
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 something like
我正在尝试编写一个将网页(及其图像)保存为 html 页面的函数。我正在使用 HttpWebRequest 请求网页内容。我的功能看起来像
void SaveUrl(string sourceURL, string savepath)
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(sourceURL);
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);
HttpWebResponse imgresponse = (HttpWebResponse)imgRequest.GetResponse();
//Code to save image
}
}
My problem here is I want to make all the webrequest in same session and dont want to create a new session with each imgRequest, as many of the images on my webpage are dynamically generated and are stored temporarily. so those images can only be fetched if I make a request in same session.
我的问题是我想在同一个会话中创建所有 webrequest 并且不想为每个 imgRequest 创建一个新会话,因为我网页上的许多图像都是动态生成的并且是临时存储的。所以只有当我在同一个会话中发出请求时才能获取这些图像。
采纳答案by Erv Walter
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.
会话通常通过使用 cookie 来工作。如果您希望所有请求都属于同一个会话,则需要在请求之间保留 cookie。为此,您可以创建一个 CookieContainer 并将其提供给每个 HttpWebRequest 对象。
Here's your code updated to use a CookieContainer:
这是您更新为使用 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
}
}