HttpClient.cs 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. //------------------------------------------------------------------------------
  2. // 此代码版权(除特别声明或在XREF结尾的命名空间的代码)归作者本人若汝棋茗所有
  3. // 源代码使用协议遵循本仓库的开源协议及附加协议,若本仓库没有设置,则按MIT开源协议授权
  4. // CSDN博客:https://blog.csdn.net/qq_40374647
  5. // 哔哩哔哩视频:https://space.bilibili.com/94253567
  6. // Gitee源代码仓库:https://gitee.com/RRQM_Home
  7. // Github源代码仓库:https://github.com/RRQM
  8. // API首页:https://www.yuque.com/rrqm/touchsocket/index
  9. // 交流QQ群:234762506
  10. // 感谢您的下载和使用
  11. //------------------------------------------------------------------------------
  12. //------------------------------------------------------------------------------
  13. using System;
  14. using System.Threading;
  15. using TouchSocket.Core;
  16. using TouchSocket.Resources;
  17. using TouchSocket.Sockets;
  18. namespace TouchSocket.Http
  19. {
  20. /// <summary>
  21. /// Http客户端
  22. /// </summary>
  23. public class HttpClient : HttpClientBase
  24. {
  25. }
  26. /// <summary>
  27. /// Http客户端基类
  28. /// </summary>
  29. public class HttpClientBase : TcpClientBase, IHttpClient
  30. {
  31. private readonly object m_requestLocker = new object();
  32. private bool m_getContent;
  33. private readonly WaitData<HttpResponse> m_waitData;
  34. /// <summary>
  35. /// 构造函数
  36. /// </summary>
  37. public HttpClientBase()
  38. {
  39. m_waitData = new WaitData<HttpResponse>();
  40. }
  41. /// <summary>
  42. /// <inheritdoc/>
  43. /// </summary>
  44. /// <param name="request"><inheritdoc/></param>
  45. /// <param name="onlyRequest"><inheritdoc/></param>
  46. /// <param name="timeout"><inheritdoc/></param>
  47. /// <param name="token"><inheritdoc/></param>
  48. /// <returns></returns>
  49. public HttpResponse Request(HttpRequest request, bool onlyRequest = false, int timeout = 10 * 1000, CancellationToken token = default)
  50. {
  51. lock (m_requestLocker)
  52. {
  53. m_getContent = false;
  54. using (ByteBlock byteBlock = new ByteBlock())
  55. {
  56. request.Build(byteBlock);
  57. m_waitData.Reset();
  58. m_waitData.SetCancellationToken(token);
  59. this.DefaultSend(byteBlock);
  60. if (onlyRequest)
  61. {
  62. return default;
  63. }
  64. switch (m_waitData.Wait(timeout))
  65. {
  66. case WaitDataStatus.SetRunning:
  67. return m_waitData.WaitResult;
  68. case WaitDataStatus.Overtime:
  69. throw new TimeoutException(TouchSocketStatus.Overtime.GetDescription());
  70. case WaitDataStatus.Canceled:
  71. return default;
  72. case WaitDataStatus.Default:
  73. case WaitDataStatus.Disposed:
  74. default:
  75. throw new Exception(TouchSocketStatus.UnknownError.GetDescription());
  76. }
  77. }
  78. }
  79. }
  80. /// <summary>
  81. /// <inheritdoc/>
  82. /// </summary>
  83. /// <param name="request"></param>
  84. /// <param name="onlyRequest"></param>
  85. /// <param name="timeout"></param>
  86. /// <param name="token"></param>
  87. /// <returns></returns>
  88. public HttpResponse RequestContent(HttpRequest request, bool onlyRequest = false, int timeout = 10 * 1000, CancellationToken token = default)
  89. {
  90. lock (m_requestLocker)
  91. {
  92. m_getContent = true;
  93. using (ByteBlock byteBlock = new ByteBlock())
  94. {
  95. request.Build(byteBlock);
  96. m_waitData.Reset();
  97. m_waitData.SetCancellationToken(token);
  98. this.DefaultSend(byteBlock);
  99. if (onlyRequest)
  100. {
  101. return default;
  102. }
  103. switch (m_waitData.Wait(timeout))
  104. {
  105. case WaitDataStatus.SetRunning:
  106. return m_waitData.WaitResult;
  107. case WaitDataStatus.Overtime:
  108. throw new TimeoutException(TouchSocketStatus.Overtime.GetDescription());
  109. case WaitDataStatus.Canceled:
  110. return default;
  111. case WaitDataStatus.Default:
  112. case WaitDataStatus.Disposed:
  113. default:
  114. throw new Exception(TouchSocketStatus.UnknownError.GetDescription());
  115. }
  116. }
  117. }
  118. }
  119. /// <summary>
  120. /// <inheritdoc/>
  121. /// </summary>
  122. /// <param name="disposing"></param>
  123. protected override void Dispose(bool disposing)
  124. {
  125. m_waitData?.Dispose();
  126. base.Dispose(disposing);
  127. }
  128. /// <summary>
  129. /// <inheritdoc/>
  130. /// </summary>
  131. /// <param name="timeout"></param>
  132. /// <returns></returns>
  133. public override ITcpClient Connect(int timeout = 5000)
  134. {
  135. if (Config.GetValue<HttpProxy>(HttpConfigExtensions.HttpProxyProperty) is HttpProxy httpProxy)
  136. {
  137. IPHost proxyHost = httpProxy.Host;
  138. var credential = httpProxy.Credential;
  139. IPHost remoteHost = Config.GetValue<IPHost>(TouchSocketConfigExtension.RemoteIPHostProperty);
  140. try
  141. {
  142. Config.SetRemoteIPHost(proxyHost);
  143. base.Connect(timeout);
  144. HttpRequest httpRequest = new HttpRequest();
  145. httpRequest.InitHeaders()
  146. .SetHost(remoteHost.Host)
  147. .SetUrl(remoteHost.Host, true)
  148. .AsMethod("CONNECT");
  149. var response = Request(httpRequest, timeout: timeout);
  150. if (response.IsProxyAuthenticationRequired)
  151. {
  152. if (credential is null)
  153. {
  154. throw new Exception("未指定代理的凭据。");
  155. }
  156. string authHeader = response.GetHeader(HttpHeaders.ProxyAuthenticate);
  157. if (authHeader.IsNullOrEmpty())
  158. {
  159. throw new Exception("未指定代理身份验证质询。");
  160. }
  161. var ares = new AuthenticationChallenge(authHeader, credential);
  162. httpRequest.SetHeader(HttpHeaders.ProxyAuthorization, ares.ToString());
  163. if (response.CloseConnection)
  164. {
  165. base.Close("代理要求关闭连接,随后重写连接。");
  166. base.Connect(timeout);
  167. }
  168. response = Request(httpRequest, timeout: timeout);
  169. }
  170. if (response.StatusCode != "200")
  171. {
  172. throw new Exception(response.StatusMessage);
  173. }
  174. }
  175. finally
  176. {
  177. Config.SetRemoteIPHost(remoteHost);
  178. }
  179. }
  180. else
  181. {
  182. base.Connect(timeout);
  183. }
  184. return this;
  185. }
  186. /// <summary>
  187. /// <inheritdoc/>
  188. /// </summary>
  189. /// <param name="byteBlock"></param>
  190. /// <param name="requestInfo"></param>
  191. protected override void HandleReceivedData(ByteBlock byteBlock, IRequestInfo requestInfo)
  192. {
  193. base.HandleReceivedData(byteBlock, requestInfo);
  194. if (requestInfo is HttpResponse response)
  195. {
  196. if (m_getContent)
  197. {
  198. response.TryGetContent(out _);
  199. }
  200. m_waitData.Set(response);
  201. }
  202. }
  203. /// <summary>
  204. /// <inheritdoc/>
  205. /// </summary>
  206. /// <param name="e"></param>
  207. protected override void OnConnecting(ConnectingEventArgs e)
  208. {
  209. Protocol = Protocol.Http;
  210. SetDataHandlingAdapter(new HttpClientDataHandlingAdapter());
  211. base.OnConnecting(e);
  212. }
  213. }
  214. }