HttpClientEx.cs 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. using System;
  2. using System.IO;
  3. using System.Net;
  4. #if XAMCORE_2_0
  5. using CoreFoundation;
  6. using Foundation;
  7. using ObjCRuntime;
  8. #elif MONOMAC
  9. using MonoMac.CoreFoundation;
  10. using MonoMac.Foundation;
  11. using MonoMac.ObjCRuntime;
  12. #else
  13. using MonoTouch.CoreFoundation;
  14. using MonoTouch.Foundation;
  15. using MonoTouch.ObjCRuntime;
  16. #endif
  17. #if SYSTEM_NET_HTTP && !MONOMAC
  18. namespace System.Net.Http {
  19. public partial class HttpClient {
  20. public HttpClient ()
  21. : this (GetDefaultHandler (), true)
  22. {
  23. }
  24. // note: the linker will re-write this to only reference the selected handler
  25. // but we want this to work "as expected" even if the application is not being linked
  26. static HttpMessageHandler GetDefaultHandler ()
  27. {
  28. return RuntimeOptions.GetHttpMessageHandler ();
  29. }
  30. }
  31. #else
  32. // due to historical reasons (around CFNetwork) Xamarin.Mac includes this inside it's profile assembly
  33. // and not a custom System.Net.Http assembly
  34. namespace Foundation {
  35. #endif
  36. partial class NSUrlSessionHandler {
  37. bool allowAutoRedirect;
  38. ICredentials credentials;
  39. bool sentRequest;
  40. public bool AllowAutoRedirect {
  41. get {
  42. return allowAutoRedirect;
  43. }
  44. set {
  45. EnsureModifiability ();
  46. allowAutoRedirect = value;
  47. }
  48. }
  49. public ICredentials Credentials {
  50. get {
  51. return credentials;
  52. }
  53. set {
  54. EnsureModifiability ();
  55. credentials = value;
  56. }
  57. }
  58. internal void EnsureModifiability ()
  59. {
  60. if (sentRequest)
  61. throw new InvalidOperationException (
  62. "This instance has already started one or more requests. " +
  63. "Properties can only be modified before sending the first request.");
  64. }
  65. // almost identical to ModernHttpClient version but it uses the constants from monotouch.dll | Xamarin.[iOS|WatchOS|TVOS].dll
  66. static Exception createExceptionForNSError(NSError error)
  67. {
  68. var webExceptionStatus = WebExceptionStatus.UnknownError;
  69. var innerException = new NSErrorException(error);
  70. // errors that exists in both share the same error code, so we can use a single switch/case
  71. // this also ease watchOS integration as if does not expose CFNetwork but (I would not be
  72. // surprised if it)could return some of it's error codes
  73. #if MONOTOUCH_WATCH
  74. if (error.Domain == NSError.NSUrlErrorDomain) {
  75. #else
  76. if ((error.Domain == NSError.NSUrlErrorDomain) || (error.Domain == NSError.CFNetworkErrorDomain)) {
  77. #endif
  78. // Parse the enum into a web exception status or exception. Some
  79. // of these values don't necessarily translate completely to
  80. // what WebExceptionStatus supports, so made some best guesses
  81. // here. For your reading pleasure, compare these:
  82. //
  83. // Apple docs: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Constants/index.html#//apple_ref/doc/constant_group/URL_Loading_System_Error_Codes
  84. // .NET docs: http://msdn.microsoft.com/en-us/library/system.net.webexceptionstatus(v=vs.110).aspx
  85. switch ((NSUrlError) (long) error.Code) {
  86. case NSUrlError.Cancelled:
  87. case NSUrlError.UserCancelledAuthentication:
  88. #if !MONOTOUCH_WATCH
  89. case (NSUrlError) NSNetServicesStatus.CancelledError:
  90. #endif
  91. // No more processing is required so just return.
  92. return new OperationCanceledException(error.LocalizedDescription, innerException);
  93. case NSUrlError.BadURL:
  94. case NSUrlError.UnsupportedURL:
  95. case NSUrlError.CannotConnectToHost:
  96. case NSUrlError.ResourceUnavailable:
  97. case NSUrlError.NotConnectedToInternet:
  98. case NSUrlError.UserAuthenticationRequired:
  99. case NSUrlError.InternationalRoamingOff:
  100. case NSUrlError.CallIsActive:
  101. case NSUrlError.DataNotAllowed:
  102. #if !MONOTOUCH_WATCH
  103. case (NSUrlError) CFNetworkErrors.Socks5BadCredentials:
  104. case (NSUrlError) CFNetworkErrors.Socks5UnsupportedNegotiationMethod:
  105. case (NSUrlError) CFNetworkErrors.Socks5NoAcceptableMethod:
  106. case (NSUrlError) CFNetworkErrors.HttpAuthenticationTypeUnsupported:
  107. case (NSUrlError) CFNetworkErrors.HttpBadCredentials:
  108. case (NSUrlError) CFNetworkErrors.HttpBadURL:
  109. #endif
  110. webExceptionStatus = WebExceptionStatus.ConnectFailure;
  111. break;
  112. case NSUrlError.TimedOut:
  113. #if !MONOTOUCH_WATCH
  114. case (NSUrlError) CFNetworkErrors.NetServiceTimeout:
  115. #endif
  116. webExceptionStatus = WebExceptionStatus.Timeout;
  117. break;
  118. case NSUrlError.CannotFindHost:
  119. case NSUrlError.DNSLookupFailed:
  120. #if !MONOTOUCH_WATCH
  121. case (NSUrlError) CFNetworkErrors.HostNotFound:
  122. case (NSUrlError) CFNetworkErrors.NetServiceDnsServiceFailure:
  123. #endif
  124. webExceptionStatus = WebExceptionStatus.NameResolutionFailure;
  125. break;
  126. case NSUrlError.DataLengthExceedsMaximum:
  127. webExceptionStatus = WebExceptionStatus.MessageLengthLimitExceeded;
  128. break;
  129. case NSUrlError.NetworkConnectionLost:
  130. #if !MONOTOUCH_WATCH
  131. case (NSUrlError) CFNetworkErrors.HttpConnectionLost:
  132. #endif
  133. webExceptionStatus = WebExceptionStatus.ConnectionClosed;
  134. break;
  135. case NSUrlError.HTTPTooManyRedirects:
  136. case NSUrlError.RedirectToNonExistentLocation:
  137. #if !MONOTOUCH_WATCH
  138. case (NSUrlError) CFNetworkErrors.HttpRedirectionLoopDetected:
  139. #endif
  140. webExceptionStatus = WebExceptionStatus.ProtocolError;
  141. break;
  142. case NSUrlError.RequestBodyStreamExhausted:
  143. #if !MONOTOUCH_WATCH
  144. case (NSUrlError) CFNetworkErrors.SocksUnknownClientVersion:
  145. case (NSUrlError) CFNetworkErrors.SocksUnsupportedServerVersion:
  146. case (NSUrlError) CFNetworkErrors.HttpParseFailure:
  147. #endif
  148. webExceptionStatus = WebExceptionStatus.SendFailure;
  149. break;
  150. case NSUrlError.BadServerResponse:
  151. case NSUrlError.ZeroByteResource:
  152. case NSUrlError.CannotDecodeRawData:
  153. case NSUrlError.CannotDecodeContentData:
  154. case NSUrlError.CannotParseResponse:
  155. case NSUrlError.FileDoesNotExist:
  156. case NSUrlError.FileIsDirectory:
  157. case NSUrlError.NoPermissionsToReadFile:
  158. case NSUrlError.CannotLoadFromNetwork:
  159. case NSUrlError.CannotCreateFile:
  160. case NSUrlError.CannotOpenFile:
  161. case NSUrlError.CannotCloseFile:
  162. case NSUrlError.CannotWriteToFile:
  163. case NSUrlError.CannotRemoveFile:
  164. case NSUrlError.CannotMoveFile:
  165. case NSUrlError.DownloadDecodingFailedMidStream:
  166. case NSUrlError.DownloadDecodingFailedToComplete:
  167. #if !MONOTOUCH_WATCH
  168. case (NSUrlError) CFNetworkErrors.Socks4RequestFailed:
  169. case (NSUrlError) CFNetworkErrors.Socks4IdentdFailed:
  170. case (NSUrlError) CFNetworkErrors.Socks4IdConflict:
  171. case (NSUrlError) CFNetworkErrors.Socks4UnknownStatusCode:
  172. case (NSUrlError) CFNetworkErrors.Socks5BadState:
  173. case (NSUrlError) CFNetworkErrors.Socks5BadResponseAddr:
  174. case (NSUrlError) CFNetworkErrors.CannotParseCookieFile:
  175. case (NSUrlError) CFNetworkErrors.NetServiceUnknown:
  176. case (NSUrlError) CFNetworkErrors.NetServiceCollision:
  177. case (NSUrlError) CFNetworkErrors.NetServiceNotFound:
  178. case (NSUrlError) CFNetworkErrors.NetServiceInProgress:
  179. case (NSUrlError) CFNetworkErrors.NetServiceBadArgument:
  180. case (NSUrlError) CFNetworkErrors.NetServiceInvalid:
  181. #endif
  182. webExceptionStatus = WebExceptionStatus.ReceiveFailure;
  183. break;
  184. case NSUrlError.SecureConnectionFailed:
  185. webExceptionStatus = WebExceptionStatus.SecureChannelFailure;
  186. break;
  187. case NSUrlError.ServerCertificateHasBadDate:
  188. case NSUrlError.ServerCertificateHasUnknownRoot:
  189. case NSUrlError.ServerCertificateNotYetValid:
  190. case NSUrlError.ServerCertificateUntrusted:
  191. case NSUrlError.ClientCertificateRejected:
  192. case NSUrlError.ClientCertificateRequired:
  193. webExceptionStatus = WebExceptionStatus.TrustFailure;
  194. break;
  195. #if !MONOTOUCH_WATCH
  196. case (NSUrlError) CFNetworkErrors.HttpProxyConnectionFailure:
  197. case (NSUrlError) CFNetworkErrors.HttpBadProxyCredentials:
  198. case (NSUrlError) CFNetworkErrors.PacFileError:
  199. case (NSUrlError) CFNetworkErrors.PacFileAuth:
  200. case (NSUrlError) CFNetworkErrors.HttpsProxyConnectionFailure:
  201. case (NSUrlError) CFNetworkErrors.HttpsProxyFailureUnexpectedResponseToConnectMethod:
  202. webExceptionStatus = WebExceptionStatus.RequestProhibitedByProxy;
  203. break;
  204. #endif
  205. }
  206. }
  207. // Always create a WebException so that it can be handled by the client.
  208. return new WebException(error.LocalizedDescription, innerException); //, webExceptionStatus, response: null);
  209. }
  210. }
  211. }