Response.cs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Net;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. namespace cuidian.OpenApi.Http
  9. {
  10. public class Response
  11. {
  12. public Response(HttpWebResponse resp)
  13. {
  14. this.HttpWebResponse = resp;
  15. }
  16. public HttpWebResponse HttpWebResponse { get; private set; }
  17. /// <summary>
  18. /// 把响应流转换为文本。
  19. /// </summary>
  20. /// <returns>响应文本</returns>
  21. public string GetResponseAsString()
  22. {
  23. Encoding encoding = Encoding.GetEncoding(this.HttpWebResponse.CharacterSet);
  24. return this.GetResponseAsString(encoding);
  25. }
  26. /// <summary>
  27. /// 把响应流转换为文本。
  28. /// </summary>
  29. /// <param name="encoding">编码方式</param>
  30. /// <returns>响应文本</returns>
  31. public string GetResponseAsString(Encoding encoding)
  32. {
  33. System.IO.Stream stream = null;
  34. StreamReader reader = null;
  35. try
  36. {
  37. // 以字符流的方式读取HTTP响应
  38. stream = this.HttpWebResponse.GetResponseStream();
  39. reader = new StreamReader(stream, encoding);
  40. return reader.ReadToEnd();
  41. }
  42. finally
  43. {
  44. // 释放资源
  45. if (reader != null) reader.Close();
  46. if (stream != null) stream.Close();
  47. if (this.HttpWebResponse != null) this.HttpWebResponse.Close();
  48. }
  49. }
  50. }
  51. }