コード例 #1
0
        /// <summary>
        /// Gets the character encoding for the response. This will look at the content of the response if it is not set in the http headers.
        /// </summary>
        /// <returns></returns>
        public Encoding GetEncoding()
        {
            try
            {
                if (!ContentEncoding.IsEmpty())
                {
                    return(Encoding.GetEncoding(ContentEncoding));
                }
                if (!CharacterSet.IsEmpty())
                {
                    return(Encoding.GetEncoding(CharacterSet));
                }

                var bytes = Result as byte[];
                if (bytes == null)
                {
                    return(Options.ResponseEncoding);
                }

                var meta = Encoding.ASCII.GetString(bytes).Trim();
                if (meta.StartsWith("<?xml"))
                {
                    var startPos = meta.IndexOf("encoding=\"");
                    if (startPos > 0)
                    {
                        var endPos  = meta.IndexOf("\"", startPos + 1);
                        var charset = meta.Substring(startPos + 10, endPos - startPos + 1);
                        charset = charset.TrimEnd(new Char[] { '>', '"', '?' });
                        return(Encoding.GetEncoding(charset));
                    }
                }
                else
                {
                    var startPos = meta.IndexOf("charset=");
                    if (startPos != -1)
                    {
                        var endPos = meta.IndexOf("\"", startPos);
                        if (endPos != -1)
                        {
                            var start   = startPos + 8;
                            var charset = meta.Substring(start, endPos - start + 1);
                            charset = charset.TrimEnd(new Char[] { '>', '"' });
                            return(Encoding.GetEncoding(charset));
                        }
                    }
                }
                return(Options.ResponseEncoding);
            }
            catch (ArgumentException ex)
            {
                // The character encoding is not a valid code page name or the code page is not supported by the underlying platform.
                // Just return the default encoding.
                Debug.WriteLine("Error getting the encoding: {0}".Fmt(ex.Message));
                return(Options.ResponseEncoding);
            }
        }