using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; namespace cuidian.OpenApi.Http { public class Response { public Response(HttpWebResponse resp) { this.HttpWebResponse = resp; } public HttpWebResponse HttpWebResponse { get; private set; } /// /// 把响应流转换为文本。 /// /// 响应文本 public string GetResponseAsString() { Encoding encoding = Encoding.GetEncoding(this.HttpWebResponse.CharacterSet); return this.GetResponseAsString(encoding); } /// /// 把响应流转换为文本。 /// /// 编码方式 /// 响应文本 public string GetResponseAsString(Encoding encoding) { System.IO.Stream stream = null; StreamReader reader = null; try { // 以字符流的方式读取HTTP响应 stream = this.HttpWebResponse.GetResponseStream(); reader = new StreamReader(stream, encoding); return reader.ReadToEnd(); } finally { // 释放资源 if (reader != null) reader.Close(); if (stream != null) stream.Close(); if (this.HttpWebResponse != null) this.HttpWebResponse.Close(); } } } }