1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907
|
// HtmlAgilityPack V1.0 - Simon Mourier <simon underscore mourier at hotmail dot com>
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.Xml.Xsl;
using Microsoft.Win32;
namespace HtmlAgilityPack
{
/// <summary>
/// A utility class to get HTML document from HTTP.
/// </summary>
public class HtmlWeb
{
#region Delegates
/// <summary>
/// Represents the method that will handle the PostResponse event.
/// </summary>
public delegate void PostResponseHandler(HttpWebRequest request, HttpWebResponse response);
/// <summary>
/// Represents the method that will handle the PreHandleDocument event.
/// </summary>
public delegate void PreHandleDocumentHandler(HtmlDocument document);
/// <summary>
/// Represents the method that will handle the PreRequest event.
/// </summary>
public delegate bool PreRequestHandler(HttpWebRequest request);
#endregion
#region Fields
private bool _autoDetectEncoding = true;
private bool _cacheOnly;
private string _cachePath;
private bool _fromCache;
private int _requestDuration;
private Uri _responseUri;
private HttpStatusCode _statusCode = HttpStatusCode.OK;
private int _streamBufferSize = 1024;
private bool _useCookies;
private bool _usingCache;
/// <summary>
/// Occurs after an HTTP request has been executed.
/// </summary>
public PostResponseHandler PostResponse;
/// <summary>
/// Occurs before an HTML document is handled.
/// </summary>
public PreHandleDocumentHandler PreHandleDocument;
/// <summary>
/// Occurs before an HTTP request is executed.
/// </summary>
public PreRequestHandler PreRequest;
#endregion
#region Properties
/// <summary>
/// Gets or Sets a value indicating if document encoding must be automatically detected.
/// </summary>
public bool AutoDetectEncoding
{
get { return _autoDetectEncoding; }
set { _autoDetectEncoding = value; }
}
/// <summary>
/// Gets or Sets a value indicating whether to get document only from the cache.
/// If this is set to true and document is not found in the cache, nothing will be loaded.
/// </summary>
public bool CacheOnly
{
get { return _cacheOnly; }
set
{
if ((value) && !UsingCache)
{
throw new HtmlWebException("Cache is not enabled. Set UsingCache to true first.");
}
_cacheOnly = value;
}
}
/// <summary>
/// Gets or Sets the cache path. If null, no caching mechanism will be used.
/// </summary>
public string CachePath
{
get { return _cachePath; }
set { _cachePath = value; }
}
/// <summary>
/// Gets a value indicating if the last document was retrieved from the cache.
/// </summary>
public bool FromCache
{
get { return _fromCache; }
}
/// <summary>
/// Gets the last request duration in milliseconds.
/// </summary>
public int RequestDuration
{
get { return _requestDuration; }
}
/// <summary>
/// Gets the URI of the Internet resource that actually responded to the request.
/// </summary>
public Uri ResponseUri
{
get { return _responseUri; }
}
/// <summary>
/// Gets the last request status.
/// </summary>
public HttpStatusCode StatusCode
{
get { return _statusCode; }
}
/// <summary>
/// Gets or Sets the size of the buffer used for memory operations.
/// </summary>
public int StreamBufferSize
{
get { return _streamBufferSize; }
set
{
if (_streamBufferSize <= 0)
{
throw new ArgumentException("Size must be greater than zero.");
}
_streamBufferSize = value;
}
}
/// <summary>
/// Gets or Sets a value indicating if cookies will be stored.
/// </summary>
public bool UseCookies
{
get { return _useCookies; }
set { _useCookies = value; }
}
/// <summary>
/// Gets or Sets a value indicating whether the caching mechanisms should be used or not.
/// </summary>
public bool UsingCache
{
get
{
if (_cachePath == null)
{
return false;
}
return _usingCache;
}
set
{
if ((value) && (_cachePath == null))
{
throw new HtmlWebException("You need to define a CachePath first.");
}
_usingCache = value;
}
}
#endregion
#region Public Methods
/// <summary>
/// Gets the MIME content type for a given path extension.
/// </summary>
/// <param name="extension">The input path extension.</param>
/// <param name="def">The default content type to return if any error occurs.</param>
/// <returns>The path extension's MIME content type.</returns>
public static string GetContentTypeForExtension(string extension, string def)
{
if (string.IsNullOrEmpty(extension))
{
return def;
}
string contentType = "";
try
{
RegistryKey reg = Registry.ClassesRoot;
reg = reg.OpenSubKey(extension, false);
if (reg != null) contentType = (string)reg.GetValue("", def);
}
catch (Exception)
{
contentType = def;
}
return contentType;
}
/// <summary>
/// Gets the path extension for a given MIME content type.
/// </summary>
/// <param name="contentType">The input MIME content type.</param>
/// <param name="def">The default path extension to return if any error occurs.</param>
/// <returns>The MIME content type's path extension.</returns>
public static string GetExtensionForContentType(string contentType, string def)
{
if (string.IsNullOrEmpty(contentType))
{
return def;
}
string ext = "";
try
{
RegistryKey reg = Registry.ClassesRoot;
reg = reg.OpenSubKey(@"MIME\Database\Content Type\" + contentType, false);
if (reg != null) ext = (string)reg.GetValue("Extension", def);
}
catch (Exception)
{
ext = def;
}
return ext;
}
/// <summary>
/// Creates an instance of the given type from the specified Internet resource.
/// </summary>
/// <param name="url">The requested URL, such as "http://Myserver/Mypath/Myfile.asp".</param>
/// <param name="type">The requested type.</param>
/// <returns>An newly created instance.</returns>
public object CreateInstance(string url, Type type)
{
return CreateInstance(url, null, null, type);
}
/// <summary>
/// Creates an instance of the given type from the specified Internet resource.
/// </summary>
/// <param name="htmlUrl">The requested URL, such as "http://Myserver/Mypath/Myfile.asp".</param>
/// <param name="xsltUrl">The URL that specifies the XSLT stylesheet to load.</param>
/// <param name="xsltArgs">An <see cref="XsltArgumentList"/> containing the namespace-qualified arguments used as input to the transform.</param>
/// <param name="type">The requested type.</param>
/// <returns>An newly created instance.</returns>
public object CreateInstance(string htmlUrl, string xsltUrl, XsltArgumentList xsltArgs, Type type)
{
return CreateInstance(htmlUrl, xsltUrl, xsltArgs, type, null);
}
/// <summary>
/// Creates an instance of the given type from the specified Internet resource.
/// </summary>
/// <param name="htmlUrl">The requested URL, such as "http://Myserver/Mypath/Myfile.asp".</param>
/// <param name="xsltUrl">The URL that specifies the XSLT stylesheet to load.</param>
/// <param name="xsltArgs">An <see cref="XsltArgumentList"/> containing the namespace-qualified arguments used as input to the transform.</param>
/// <param name="type">The requested type.</param>
/// <param name="xmlPath">A file path where the temporary XML before transformation will be saved. Mostly used for debugging purposes.</param>
/// <returns>An newly created instance.</returns>
public object CreateInstance(string htmlUrl, string xsltUrl, XsltArgumentList xsltArgs, Type type,
string xmlPath)
{
StringWriter sw = new StringWriter();
XmlTextWriter writer = new XmlTextWriter(sw);
if (xsltUrl == null)
{
LoadHtmlAsXml(htmlUrl, writer);
}
else
{
if (xmlPath == null)
{
LoadHtmlAsXml(htmlUrl, xsltUrl, xsltArgs, writer);
}
else
{
LoadHtmlAsXml(htmlUrl, xsltUrl, xsltArgs, writer, xmlPath);
}
}
writer.Flush();
StringReader sr = new StringReader(sw.ToString());
XmlTextReader reader = new XmlTextReader(sr);
XmlSerializer serializer = new XmlSerializer(type);
object o;
try
{
o = serializer.Deserialize(reader);
}
catch (InvalidOperationException ex)
{
throw new Exception(ex + ", --- xml:" + sw);
}
return o;
}
/// <summary>
/// Gets an HTML document from an Internet resource and saves it to the specified file.
/// </summary>
/// <param name="url">The requested URL, such as "http://Myserver/Mypath/Myfile.asp".</param>
/// <param name="path">The location of the file where you want to save the document.</param>
public void Get(string url, string path)
{
Get(url, path, "GET");
}
/// <summary>
/// Gets an HTML document from an Internet resource and saves it to the specified file. - Proxy aware
/// </summary>
/// <param name="url">The requested URL, such as "http://Myserver/Mypath/Myfile.asp".</param>
/// <param name="path">The location of the file where you want to save the document.</param>
/// <param name="proxy"></param>
/// <param name="credentials"></param>
public void Get(string url, string path, WebProxy proxy, NetworkCredential credentials)
{
Get(url, path, proxy, credentials, "GET");
}
/// <summary>
/// Gets an HTML document from an Internet resource and saves it to the specified file.
/// </summary>
/// <param name="url">The requested URL, such as "http://Myserver/Mypath/Myfile.asp".</param>
/// <param name="path">The location of the file where you want to save the document.</param>
/// <param name="method">The HTTP method used to open the connection, such as GET, POST, PUT, or PROPFIND.</param>
public void Get(string url, string path, string method)
{
Uri uri = new Uri(url);
if ((uri.Scheme == Uri.UriSchemeHttps) ||
(uri.Scheme == Uri.UriSchemeHttp))
{
Get(uri, method, path, null, null, null);
}
else
{
throw new HtmlWebException("Unsupported uri scheme: '" + uri.Scheme + "'.");
}
}
/// <summary>
/// Gets an HTML document from an Internet resource and saves it to the specified file. Understands Proxies
/// </summary>
/// <param name="url">The requested URL, such as "http://Myserver/Mypath/Myfile.asp".</param>
/// <param name="path">The location of the file where you want to save the document.</param>
/// <param name="credentials"></param>
/// <param name="method">The HTTP method used to open the connection, such as GET, POST, PUT, or PROPFIND.</param>
/// <param name="proxy"></param>
public void Get(string url, string path, WebProxy proxy, NetworkCredential credentials, string method)
{
Uri uri = new Uri(url);
if ((uri.Scheme == Uri.UriSchemeHttps) ||
(uri.Scheme == Uri.UriSchemeHttp))
{
Get(uri, method, path, null, proxy, credentials);
}
else
{
throw new HtmlWebException("Unsupported uri scheme: '" + uri.Scheme + "'.");
}
}
/// <summary>
/// Gets the cache file path for a specified url.
/// </summary>
/// <param name="uri">The url fo which to retrieve the cache path. May not be null.</param>
/// <returns>The cache file path.</returns>
public string GetCachePath(Uri uri)
{
if (uri == null)
{
throw new ArgumentNullException("uri");
}
if (!UsingCache)
{
throw new HtmlWebException("Cache is not enabled. Set UsingCache to true first.");
}
string cachePath;
if (uri.AbsolutePath == "/")
{
cachePath = Path.Combine(_cachePath, ".htm");
}
else
{
cachePath = Path.Combine(_cachePath, (uri.Host + uri.AbsolutePath).Replace('/', '\\'));
}
return cachePath;
}
/// <summary>
/// Gets an HTML document from an Internet resource.
/// </summary>
/// <param name="url">The requested URL, such as "http://Myserver/Mypath/Myfile.asp".</param>
/// <returns>A new HTML document.</returns>
public HtmlDocument Load(string url)
{
return Load(url, "GET");
}
/// <summary>
/// Gets an HTML document from an Internet resource.
/// </summary>
/// <param name="url">The requested URL, such as "http://Myserver/Mypath/Myfile.asp".</param>
/// <param name="proxyHost">Host to use for Proxy</param>
/// <param name="proxyPort">Port the Proxy is on</param>
/// <param name="userId">User Id for Authentication</param>
/// <param name="password">Password for Authentication</param>
/// <returns>A new HTML document.</returns>
public HtmlDocument Load(string url, string proxyHost, int proxyPort, string userId, string password)
{
//Create my proxy
WebProxy myProxy = new WebProxy(proxyHost, proxyPort);
myProxy.BypassProxyOnLocal = true;
//Create my credentials
NetworkCredential myCreds = null;
if ((userId != null) && (password != null))
{
myCreds = new NetworkCredential(userId, password);
CredentialCache credCache = new CredentialCache();
//Add the creds
credCache.Add(myProxy.Address, "Basic", myCreds);
credCache.Add(myProxy.Address, "Digest", myCreds);
}
return Load(url, "GET", myProxy, myCreds);
}
/// <summary>
/// Loads an HTML document from an Internet resource.
/// </summary>
/// <param name="url">The requested URL, such as "http://Myserver/Mypath/Myfile.asp".</param>
/// <param name="method">The HTTP method used to open the connection, such as GET, POST, PUT, or PROPFIND.</param>
/// <returns>A new HTML document.</returns>
public HtmlDocument Load(string url, string method)
{
Uri uri = new Uri(url);
HtmlDocument doc;
if ((uri.Scheme == Uri.UriSchemeHttps) ||
(uri.Scheme == Uri.UriSchemeHttp))
{
doc = LoadUrl(uri, method, null, null);
}
else
{
if (uri.Scheme == Uri.UriSchemeFile)
{
doc = new HtmlDocument();
doc.OptionAutoCloseOnEnd = false;
doc.OptionAutoCloseOnEnd = true;
doc.DetectEncodingAndLoad(url, _autoDetectEncoding);
}
else
{
throw new HtmlWebException("Unsupported uri scheme: '" + uri.Scheme + "'.");
}
}
if (PreHandleDocument != null)
{
PreHandleDocument(doc);
}
return doc;
}
/// <summary>
/// Loads an HTML document from an Internet resource.
/// </summary>
/// <param name="url">The requested URL, such as "http://Myserver/Mypath/Myfile.asp".</param>
/// <param name="method">The HTTP method used to open the connection, such as GET, POST, PUT, or PROPFIND.</param>
/// <param name="proxy">Proxy to use with this request</param>
/// <param name="credentials">Credentials to use when authenticating</param>
/// <returns>A new HTML document.</returns>
public HtmlDocument Load(string url, string method, WebProxy proxy, NetworkCredential credentials)
{
Uri uri = new Uri(url);
HtmlDocument doc;
if ((uri.Scheme == Uri.UriSchemeHttps) ||
(uri.Scheme == Uri.UriSchemeHttp))
{
doc = LoadUrl(uri, method, proxy, credentials);
}
else
{
if (uri.Scheme == Uri.UriSchemeFile)
{
doc = new HtmlDocument();
doc.OptionAutoCloseOnEnd = false;
doc.OptionAutoCloseOnEnd = true;
doc.DetectEncodingAndLoad(url, _autoDetectEncoding);
}
else
{
throw new HtmlWebException("Unsupported uri scheme: '" + uri.Scheme + "'.");
}
}
if (PreHandleDocument != null)
{
PreHandleDocument(doc);
}
return doc;
}
/// <summary>
/// Loads an HTML document from an Internet resource and saves it to the specified XmlTextWriter.
/// </summary>
/// <param name="htmlUrl">The requested URL, such as "http://Myserver/Mypath/Myfile.asp".</param>
/// <param name="writer">The XmlTextWriter to which you want to save.</param>
public void LoadHtmlAsXml(string htmlUrl, XmlTextWriter writer)
{
HtmlDocument doc = Load(htmlUrl);
doc.Save(writer);
}
/// <summary>
/// Loads an HTML document from an Internet resource and saves it to the specified XmlTextWriter, after an XSLT transformation.
/// </summary>
/// <param name="htmlUrl">The requested URL, such as "http://Myserver/Mypath/Myfile.asp".</param>
/// <param name="xsltUrl">The URL that specifies the XSLT stylesheet to load.</param>
/// <param name="xsltArgs">An XsltArgumentList containing the namespace-qualified arguments used as input to the transform.</param>
/// <param name="writer">The XmlTextWriter to which you want to save.</param>
public void LoadHtmlAsXml(string htmlUrl, string xsltUrl, XsltArgumentList xsltArgs, XmlTextWriter writer)
{
LoadHtmlAsXml(htmlUrl, xsltUrl, xsltArgs, writer, null);
}
/// <summary>
/// Loads an HTML document from an Internet resource and saves it to the specified XmlTextWriter, after an XSLT transformation.
/// </summary>
/// <param name="htmlUrl">The requested URL, such as "http://Myserver/Mypath/Myfile.asp". May not be null.</param>
/// <param name="xsltUrl">The URL that specifies the XSLT stylesheet to load.</param>
/// <param name="xsltArgs">An XsltArgumentList containing the namespace-qualified arguments used as input to the transform.</param>
/// <param name="writer">The XmlTextWriter to which you want to save.</param>
/// <param name="xmlPath">A file path where the temporary XML before transformation will be saved. Mostly used for debugging purposes.</param>
public void LoadHtmlAsXml(string htmlUrl, string xsltUrl, XsltArgumentList xsltArgs, XmlTextWriter writer,
string xmlPath)
{
if (htmlUrl == null)
{
throw new ArgumentNullException("htmlUrl");
}
HtmlDocument doc = Load(htmlUrl);
if (xmlPath != null)
{
XmlTextWriter w = new XmlTextWriter(xmlPath, doc.Encoding);
doc.Save(w);
w.Close();
}
if (xsltArgs == null)
{
xsltArgs = new XsltArgumentList();
}
// add some useful variables to the xslt doc
xsltArgs.AddParam("url", "", htmlUrl);
xsltArgs.AddParam("requestDuration", "", RequestDuration);
xsltArgs.AddParam("fromCache", "", FromCache);
XslCompiledTransform xslt = new XslCompiledTransform();
xslt.Load(xsltUrl);
xslt.Transform(doc, xsltArgs, writer);
}
#endregion
#region Private Methods
private static void FilePreparePath(string target)
{
if (File.Exists(target))
{
FileAttributes atts = File.GetAttributes(target);
File.SetAttributes(target, atts & ~FileAttributes.ReadOnly);
}
else
{
string dir = Path.GetDirectoryName(target);
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
}
}
private static DateTime RemoveMilliseconds(DateTime t)
{
return new DateTime(t.Year, t.Month, t.Day, t.Hour, t.Minute, t.Second, 0);
}
// ReSharper disable UnusedMethodReturnValue.Local
private static long SaveStream(Stream stream, string path, DateTime touchDate, int streamBufferSize)
// ReSharper restore UnusedMethodReturnValue.Local
{
FilePreparePath(path);
FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write);
BinaryReader br = null;
BinaryWriter bw = null;
long len = 0;
try
{
br = new BinaryReader(stream);
bw = new BinaryWriter(fs);
byte[] buffer;
do
{
buffer = br.ReadBytes(streamBufferSize);
len += buffer.Length;
if (buffer.Length > 0)
{
bw.Write(buffer);
}
} while (buffer.Length > 0);
}
finally
{
if (br != null)
{
br.Close();
}
if (bw != null)
{
bw.Flush();
bw.Close();
}
if (fs != null)
{
fs.Close();
}
}
File.SetLastWriteTime(path, touchDate);
return len;
}
private HttpStatusCode Get(Uri uri, string method, string path, HtmlDocument doc, IWebProxy proxy,
ICredentials creds)
{
string cachePath = null;
HttpWebRequest req;
bool oldFile = false;
req = WebRequest.Create(uri) as HttpWebRequest;
req.Method = method;
if (proxy != null)
{
if (creds != null)
{
proxy.Credentials = creds;
req.Credentials = creds;
}
else
{
proxy.Credentials = CredentialCache.DefaultCredentials;
req.Credentials = CredentialCache.DefaultCredentials;
}
req.Proxy = proxy;
}
_fromCache = false;
_requestDuration = 0;
int tc = Environment.TickCount;
if (UsingCache)
{
cachePath = GetCachePath(req.RequestUri);
if (File.Exists(cachePath))
{
req.IfModifiedSince = File.GetLastAccessTime(cachePath);
oldFile = true;
}
}
if (_cacheOnly)
{
if (!File.Exists(cachePath))
{
throw new HtmlWebException("File was not found at cache path: '" + cachePath + "'");
}
if (path != null)
{
IOLibrary.CopyAlways(cachePath, path);
// touch the file
File.SetLastWriteTime(path, File.GetLastWriteTime(cachePath));
}
_fromCache = true;
return HttpStatusCode.NotModified;
}
if (_useCookies)
{
req.CookieContainer = new CookieContainer();
}
if (PreRequest != null)
{
// allow our user to change the request at will
if (!PreRequest(req))
{
return HttpStatusCode.ResetContent;
}
// dump cookie
// if (_useCookies)
// {
// foreach(Cookie cookie in req.CookieContainer.GetCookies(req.RequestUri))
// {
// HtmlLibrary.Trace("Cookie " + cookie.Name + "=" + cookie.Value + " path=" + cookie.Path + " domain=" + cookie.Domain);
// }
// }
}
HttpWebResponse resp;
try
{
resp = req.GetResponse() as HttpWebResponse;
}
catch (WebException we)
{
_requestDuration = Environment.TickCount - tc;
resp = (HttpWebResponse)we.Response;
if (resp == null)
{
if (oldFile)
{
if (path != null)
{
IOLibrary.CopyAlways(cachePath, path);
// touch the file
File.SetLastWriteTime(path, File.GetLastWriteTime(cachePath));
}
return HttpStatusCode.NotModified;
}
throw;
}
}
catch (Exception)
{
_requestDuration = Environment.TickCount - tc;
throw;
}
// allow our user to get some info from the response
if (PostResponse != null)
{
PostResponse(req, resp);
}
_requestDuration = Environment.TickCount - tc;
_responseUri = resp.ResponseUri;
bool html = IsHtmlContent(resp.ContentType);
Encoding respenc;
if ((resp.ContentEncoding != null) && (resp.ContentEncoding.Length > 0))
{
respenc = Encoding.GetEncoding(resp.ContentEncoding);
}
else
{
respenc = null;
}
if (resp.StatusCode == HttpStatusCode.NotModified)
{
if (UsingCache)
{
_fromCache = true;
if (path != null)
{
IOLibrary.CopyAlways(cachePath, path);
// touch the file
File.SetLastWriteTime(path, File.GetLastWriteTime(cachePath));
}
return resp.StatusCode;
}
else
{
// this should *never* happen...
throw new HtmlWebException("Server has send a NotModifed code, without cache enabled.");
}
}
Stream s = resp.GetResponseStream();
if (s != null)
{
if (UsingCache)
{
// NOTE: LastModified does not contain milliseconds, so we remove them to the file
SaveStream(s, cachePath, RemoveMilliseconds(resp.LastModified), _streamBufferSize);
// save headers
SaveCacheHeaders(req.RequestUri, resp);
if (path != null)
{
// copy and touch the file
IOLibrary.CopyAlways(cachePath, path);
File.SetLastWriteTime(path, File.GetLastWriteTime(cachePath));
}
}
else
{
// try to work in-memory
if ((doc != null) && (html))
{
if (respenc != null)
{
doc.Load(s, respenc);
}
else
{
doc.Load(s, true);
}
}
}
resp.Close();
}
return resp.StatusCode;
}
private string GetCacheHeader(Uri requestUri, string name, string def)
{
// note: some headers are collection (ex: www-authenticate)
// we don't handle that here
XmlDocument doc = new XmlDocument();
doc.Load(GetCacheHeadersPath(requestUri));
XmlNode node =
doc.SelectSingleNode("//h[translate(@n, 'abcdefghijklmnopqrstuvwxyz','ABCDEFGHIJKLMNOPQRSTUVWXYZ')='" +
name.ToUpper() + "']");
if (node == null)
{
return def;
}
// attribute should exist
return node.Attributes[name].Value;
}
private string GetCacheHeadersPath(Uri uri)
{
//return Path.Combine(GetCachePath(uri), ".h.xml");
return GetCachePath(uri) + ".h.xml";
}
private bool IsCacheHtmlContent(string path)
{
string ct = GetContentTypeForExtension(Path.GetExtension(path), null);
return IsHtmlContent(ct);
}
private bool IsHtmlContent(string contentType)
{
return contentType.ToLower().StartsWith("text/html");
}
private HtmlDocument LoadUrl(Uri uri, string method, WebProxy proxy, NetworkCredential creds)
{
HtmlDocument doc = new HtmlDocument();
doc.OptionAutoCloseOnEnd = false;
doc.OptionFixNestedTags = true;
_statusCode = Get(uri, method, null, doc, proxy, creds);
if (_statusCode == HttpStatusCode.NotModified)
{
// read cached encoding
doc.DetectEncodingAndLoad(GetCachePath(uri));
}
return doc;
}
private void SaveCacheHeaders(Uri requestUri, HttpWebResponse resp)
{
// we cache the original headers aside the cached document.
string file = GetCacheHeadersPath(requestUri);
XmlDocument doc = new XmlDocument();
doc.LoadXml("<c></c>");
XmlNode cache = doc.FirstChild;
foreach (string header in resp.Headers)
{
XmlNode entry = doc.CreateElement("h");
XmlAttribute att = doc.CreateAttribute("n");
att.Value = header;
entry.Attributes.Append(att);
att = doc.CreateAttribute("v");
att.Value = resp.Headers[header];
entry.Attributes.Append(att);
cache.AppendChild(entry);
}
doc.Save(file);
}
#endregion
}
}
|