Esempio n. 1
0
        /// <summary>
        /// Reads an <see cref="HttpWebResponse"/> as plain text.
        /// </summary>
        /// <param name="webResponse">
        /// The <see cref="HttpWebResponse"/> to read.
        /// </param>
        /// <param name="encoding">
        /// The encoding to be used. If omitted, the encoding specified in the web response shall be used.
        /// </param>
        /// <returns>
        /// A <see cref="string"/> that represents the text of an <see cref="HttpWebResponse"/>.
        /// </returns>
        public static string GetResponseText(this HttpWebResponse webResponse, Encoding encoding = null)
        {
            if (encoding == null)
            {
                encoding = webResponse.GetEncoding();
            }

            var s = webResponse.GetResponseStream();

            if (s != null)
            {
                StreamReader sr;

                if (webResponse.Headers[HttpResponseHeader.ContentEncoding] == "gzip")
                {
                    sr = new StreamReader(new GZipStream(s, CompressionMode.Decompress), encoding);
                }
                else
                {
                    sr = new StreamReader(s, encoding);
                }

                var content = sr.ReadToEnd();

                sr.Dispose();

                return(content);
            }

            return(null);
        }
        private static string GetString(this HttpWebResponse response, byte[] bytes)
        {
            var encoding = response.GetEncoding();
            var result   = encoding.GetString(bytes);

            if (response.IsEmptyCharacterSet())
            {
                string charset;
                if (result.TryGetMatchValue(@"charset\b\s*=\s*(?<charset>[^""]+)", out charset))
                {
                    var charsetEncoding = Encoding.GetEncoding(charset);
                    if (!charsetEncoding.Equals(encoding))
                    {
                        CharacterSetCache[response.ResponseUri.Host] = encoding;
                        return(charsetEncoding.GetString(bytes));
                    }
                }
            }
            CharacterSetCache[response.ResponseUri.Host] = encoding;
            return(result);
        }
Esempio n. 3
0
 public static Encoding GetEncoding(HttpWebResponse webResponse)
 {
     return(webResponse.GetEncoding());
 }