2 // System.Net.HttpWebResponse
5 // Lawrence Pit (loz@cable.a2000.nl)
6 // Gonzalo Paniagua Javier (gonzalo@ximian.com)
7 // Daniel Nauck (dna(at)mono-project(dot)de)
9 // (c) 2002 Lawrence Pit
10 // (c) 2003 Ximian, Inc. (http://www.ximian.com)
11 // (c) 2008 Daniel Nauck
15 // Permission is hereby granted, free of charge, to any person obtaining
16 // a copy of this software and associated documentation files (the
17 // "Software"), to deal in the Software without restriction, including
18 // without limitation the rights to use, copy, modify, merge, publish,
19 // distribute, sublicense, and/or sell copies of the Software, and to
20 // permit persons to whom the Software is furnished to do so, subject to
21 // the following conditions:
23 // The above copyright notice and this permission notice shall be
24 // included in all copies or substantial portions of the Software.
26 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
27 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
28 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
29 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
30 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
31 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
32 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
36 using System.Collections;
37 using System.Globalization;
39 using System.Net.Sockets;
40 using System.Runtime.Serialization;
46 public class HttpWebResponse : WebResponse, ISerializable, IDisposable
49 WebHeaderCollection webHeaders;
50 CookieCollection cookieCollection;
53 HttpStatusCode statusCode;
54 string statusDescription;
57 CookieContainer cookie_container;
64 internal HttpWebResponse (Uri uri, string method, WebConnectionData data, CookieContainer container)
68 webHeaders = data.Headers;
69 version = data.Version;
70 statusCode = (HttpStatusCode) data.StatusCode;
71 statusDescription = data.StatusDescription;
76 string cl = webHeaders ["Content-Length"];
78 if (String.IsNullOrEmpty (cl) || !Int64.TryParse (cl, out contentLength))
81 if (cl != null && cl != String.Empty)
82 contentLength = (long) UInt64.Parse (cl);
88 if (container != null) {
89 this.cookie_container = container;
95 [Obsolete ("Serialization is obsoleted for this type", false)]
97 protected HttpWebResponse (SerializationInfo serializationInfo, StreamingContext streamingContext)
99 SerializationInfo info = serializationInfo;
101 uri = (Uri) info.GetValue ("uri", typeof (Uri));
102 contentLength = info.GetInt64 ("contentLength");
103 contentType = info.GetString ("contentType");
104 method = info.GetString ("method");
105 statusDescription = info.GetString ("statusDescription");
106 cookieCollection = (CookieCollection) info.GetValue ("cookieCollection", typeof (CookieCollection));
107 version = (Version) info.GetValue ("version", typeof (Version));
108 statusCode = (HttpStatusCode) info.GetValue ("statusCode", typeof (HttpStatusCode));
113 public string CharacterSet {
114 // Content-Type = "Content-Type" ":" media-type
115 // media-type = type "/" subtype *( ";" parameter )
116 // parameter = attribute "=" value
117 // 3.7.1. default is ISO-8859-1
119 string contentType = ContentType;
120 if (contentType == null)
122 string val = contentType.ToLower ();
123 int pos = val.IndexOf ("charset=");
127 int pos2 = val.IndexOf (';', pos);
129 ? contentType.Substring (pos)
130 : contentType.Substring (pos, pos2 - pos);
134 public string ContentEncoding {
137 string h = webHeaders ["Content-Encoding"];
138 return h != null ? h : "";
142 public override long ContentLength {
144 return contentLength;
148 public override string ContentType {
152 if (contentType == null)
153 contentType = webHeaders ["Content-Type"];
159 public CookieCollection Cookies {
162 if (cookieCollection == null)
163 cookieCollection = new CookieCollection ();
164 return cookieCollection;
168 cookieCollection = value;
172 public override WebHeaderCollection Headers {
182 static Exception GetMustImplement ()
184 return new NotImplementedException ();
188 public override bool IsMutuallyAuthenticated
191 throw GetMustImplement ();
196 public DateTime LastModified {
200 string dtStr = webHeaders ["Last-Modified"];
201 return MonoHttpDate.Parse (dtStr);
202 } catch (Exception) {
208 public string Method {
215 public Version ProtocolVersion {
222 public override Uri ResponseUri {
229 public string Server {
232 return webHeaders ["Server"];
236 public HttpStatusCode StatusCode {
242 public string StatusDescription {
245 return statusDescription;
251 public override int GetHashCode ()
253 return base.GetHashCode ();
257 public string GetResponseHeader (string headerName)
260 string value = webHeaders [headerName];
261 return (value != null) ? value : "";
264 internal void ReadAll ()
266 WebConnectionStream wce = stream as WebConnectionStream;
275 public override Stream GetResponseStream ()
280 if (0 == String.Compare (method, "HEAD", true)) // see par 4.3 & 9.4
286 void ISerializable.GetObjectData (SerializationInfo serializationInfo,
287 StreamingContext streamingContext)
289 GetObjectData (serializationInfo, streamingContext);
295 void GetObjectData (SerializationInfo serializationInfo,
296 StreamingContext streamingContext)
298 SerializationInfo info = serializationInfo;
300 info.AddValue ("uri", uri);
301 info.AddValue ("contentLength", contentLength);
302 info.AddValue ("contentType", contentType);
303 info.AddValue ("method", method);
304 info.AddValue ("statusDescription", statusDescription);
305 info.AddValue ("cookieCollection", cookieCollection);
306 info.AddValue ("version", version);
307 info.AddValue ("statusCode", statusCode);
312 public override void Close ()
314 ((IDisposable) this).Dispose ();
317 void IDisposable.Dispose ()
320 GC.SuppressFinalize (this);
326 void Dispose (bool disposing)
330 this.disposed = true;
333 // release managed resources
338 cookieCollection = null;
341 statusDescription = null;
344 // release unmanaged resources
351 private void CheckDisposed ()
354 throw new ObjectDisposedException (GetType ().FullName);
359 if (webHeaders == null)
362 string [] values = webHeaders.GetValues ("Set-Cookie");
363 if (values != null) {
364 foreach (string va in values)
368 values = webHeaders.GetValues ("Set-Cookie2");
369 if (values != null) {
370 foreach (string va in values)
375 void SetCookie (string header)
378 Cookie cookie = null;
379 CookieParser parser = new CookieParser (header);
381 while (parser.GetNextNameValue (out name, out val)) {
382 if ((name == null || name == "") && cookie == null)
385 if (cookie == null) {
386 cookie = new Cookie (name, val);
390 name = name.ToUpper ();
393 if (cookie.Comment == null)
394 cookie.Comment = val;
397 if (cookie.CommentUri == null)
398 cookie.CommentUri = new Uri (val);
401 cookie.Discard = true;
404 if (cookie.Domain == "")
409 cookie.HttpOnly = true;
412 case "MAX-AGE": // RFC Style Set-Cookie2
413 if (cookie.Expires == DateTime.MinValue) {
415 cookie.Expires = cookie.TimeStamp.AddSeconds (UInt32.Parse (val));
419 case "EXPIRES": // Netscape Style Set-Cookie
420 if (cookie.Expires != DateTime.MinValue)
423 cookie.Expires = TryParseCookieExpires (val);
429 if (cookie.Port == null)
433 cookie.Secure = true;
437 cookie.Version = (int) UInt32.Parse (val);
443 if (cookieCollection == null)
444 cookieCollection = new CookieCollection ();
446 if (cookie.Domain == "")
447 cookie.Domain = uri.Host;
449 cookieCollection.Add (cookie);
450 if (cookie_container != null)
451 cookie_container.Add (uri, cookie);
454 void SetCookie2 (string cookies_str)
456 string [] cookies = cookies_str.Split (',');
458 foreach (string cookie_str in cookies)
459 SetCookie (cookie_str);
462 string[] cookieExpiresFormats =
464 "ddd, dd'-'MMM'-'yyyy HH':'mm':'ss 'GMT'",
465 "ddd, dd'-'MMM'-'yy HH':'mm':'ss 'GMT'" };
467 DateTime TryParseCookieExpires (string value)
469 if (value == null || value.Length == 0)
470 return DateTime.MinValue;
472 for (int i = 0; i < cookieExpiresFormats.Length; i++)
475 DateTime cookieExpiresUtc = DateTime.ParseExact (value, cookieExpiresFormats [i], CultureInfo.InvariantCulture);
477 //convert UTC/GMT time to local time
479 cookieExpiresUtc = DateTime.SpecifyKind (cookieExpiresUtc, DateTimeKind.Utc);
480 return TimeZone.CurrentTimeZone.ToLocalTime (cookieExpiresUtc);
482 //DateTime.Kind is only available on .NET 2.0, so do some calculation
483 TimeSpan localOffset = TimeZone.CurrentTimeZone.GetUtcOffset (cookieExpiresUtc.Date);
484 return cookieExpiresUtc.Add (localOffset);
489 //If we can't parse Expires, use cookie as session cookie (expires is DateTime.MinValue)
490 return DateTime.MinValue;
499 public CookieParser (string header) : this (header, 0)
503 public CookieParser (string header, int position)
505 this.header = header;
507 this.length = header.Length;
510 public bool GetNextNameValue (out string name, out string val)
518 name = GetCookieName ();
519 if (pos < header.Length && header [pos] == '=') {
521 val = GetCookieValue ();
524 if (pos < length && header [pos] == ';')
530 string GetCookieName ()
533 while (k < length && Char.IsWhiteSpace (header [k]))
537 while (k < length && header [k] != ';' && header [k] != '=')
541 return header.Substring (begin, k - begin).Trim ();
544 string GetCookieValue ()
550 while (k < length && Char.IsWhiteSpace (header [k]))
554 if (header [k] == '"'){
558 while (k < length && header [k] != '"')
561 for (j = k; j < length && header [j] != ';'; j++)
566 while (k < length && header [k] != ';')
571 return header.Substring (begin, k - begin).Trim ();