HttpWebRequest + GetResponseStream编码

时间:2014-12-16 08:30:39

标签: c#

我如何解码HTTP流响应?

我收到此错误消息:

There was an error deserializing the object of type TEST.RootObject '�YL�' contains invalid UTF8 bytes.

这是我的代码:

HttpWebRequest request = WebRequest.Create(UrlRequest) as HttpWebRequest;
            //request.Headers.Add(HttpRequestHeader.AcceptCharset, "utf-8"); // I cannot get this to work!

            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    throw new Exception(String.Format("Server error (HTTP {0}: {1}).", response.StatusCode, response.StatusDescription));
                }

                DataContractJsonSerializerSettings settings = new DataContractJsonSerializerSettings();
                DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(RootObject));

                object objResponse = jsonSerializer.ReadObject(response.GetResponseStream());

                //// I cannot get this to work!
                //using (Stream resStream = response.GetResponseStream())
                //{
                //    StreamReader reader = new StreamReader(resStream, Encoding.UTF8);
                //    reader.ReadToEnd();

                //}
                //// test

0 个答案:

没有答案