我有一个应用程序可以创建许多Web请求来下载网站的新闻页面 (我已经测试了很多网站) 过了一会儿,我发现应用程序在获取html源代码时变慢,然后我发现HttpWebResonse无法获得响应。我只发布了完成这项工作的功能。
public PageFetchResult Fetch()
{
PageFetchResult fetchResult = new PageFetchResult();
try
{
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(URLAddress);
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
Uri requestedURI = new Uri(URLAddress);
Uri responseURI = resp.ResponseUri;
if (Uri.Equals(requestedURI, responseURI))
{
string resultHTML = "";
byte[] reqHTML = ResponseAsBytes(resp);
if (!string.IsNullOrEmpty(FetchingEncoding))
resultHTML = Encoding.GetEncoding(FetchingEncoding).GetString(reqHTML);
else if (!string.IsNullOrEmpty(resp.CharacterSet))
resultHTML = Encoding.GetEncoding(resp.CharacterSet).GetString(reqHTML);
resp.Close();
fetchResult.IsOK = true;
fetchResult.ResultHTML = resultHTML;
}
else
{
URLAddress = responseURI.AbsoluteUri;
relayPageCount++;
if (relayPageCount > 5)
{
fetchResult.IsOK = false;
fetchResult.ErrorMessage = "Maximum page redirection occured.";
return fetchResult;
}
return Fetch();
}
}
catch (Exception ex)
{
fetchResult.IsOK = false;
fetchResult.ErrorMessage = ex.Message;
}
return fetchResult;
}
任何解决方案都会非常感激
答案 0 :(得分:0)
以递归方式调用Fetch函数并始终创建HttpWebRequest,但仅在匹配url时才释放。您必须在else语句中关闭请求和响应。
答案 1 :(得分:0)
我同意@volody,而且HttpWebRequest已经有了名为MaximumAutomaticRedirections的属性,它被设置为50,你可以将它设置为5来自动实现你在这个代码中寻找的东西,它会引发异常,那将是由您的代码处理。
只需设置
request.MaximumAutomaticRedirections = 5;