PageRenderTime 55ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/IOSBoilerplate/ASIHTTPRequest.h

https://github.com/HueMachine/iOS-boilerplate
C Header | 1004 lines | 446 code | 267 blank | 291 comment | 2 complexity | 2f489c38403048fb605a25f2b77dbabf MD5 | raw file
  1. //
  2. // ASIHTTPRequest.h
  3. //
  4. // Created by Ben Copsey on 04/10/2007.
  5. // Copyright 2007-2011 All-Seeing Interactive. All rights reserved.
  6. //
  7. // A guide to the main features is available at:
  8. // http://allseeing-i.com/ASIHTTPRequest
  9. //
  10. // Portions are based on the ImageClient example from Apple:
  11. // See: http://developer.apple.com/samplecode/ImageClient/listing37.html
  12. #import <Foundation/Foundation.h>
  13. #if TARGET_OS_IPHONE
  14. #import <CFNetwork/CFNetwork.h>
  15. #if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_4_0
  16. #import <UIKit/UIKit.h> // Necessary for background task support
  17. #endif
  18. #endif
  19. #import <stdio.h>
  20. #import "ASIHTTPRequestConfig.h"
  21. #import "ASIHTTPRequestDelegate.h"
  22. #import "ASIProgressDelegate.h"
  23. #import "ASICacheDelegate.h"
  24. @class ASIDataDecompressor;
  25. extern NSString *ASIHTTPRequestVersion;
  26. // Make targeting different platforms more reliable
  27. // See: http://www.blumtnwerx.com/blog/2009/06/cross-sdk-code-hygiene-in-xcode/
  28. #ifndef __IPHONE_3_2
  29. #define __IPHONE_3_2 30200
  30. #endif
  31. #ifndef __IPHONE_4_0
  32. #define __IPHONE_4_0 40000
  33. #endif
  34. #ifndef __MAC_10_5
  35. #define __MAC_10_5 1050
  36. #endif
  37. #ifndef __MAC_10_6
  38. #define __MAC_10_6 1060
  39. #endif
  40. typedef enum _ASIAuthenticationState {
  41. ASINoAuthenticationNeededYet = 0,
  42. ASIHTTPAuthenticationNeeded = 1,
  43. ASIProxyAuthenticationNeeded = 2
  44. } ASIAuthenticationState;
  45. typedef enum _ASINetworkErrorType {
  46. ASIConnectionFailureErrorType = 1,
  47. ASIRequestTimedOutErrorType = 2,
  48. ASIAuthenticationErrorType = 3,
  49. ASIRequestCancelledErrorType = 4,
  50. ASIUnableToCreateRequestErrorType = 5,
  51. ASIInternalErrorWhileBuildingRequestType = 6,
  52. ASIInternalErrorWhileApplyingCredentialsType = 7,
  53. ASIFileManagementError = 8,
  54. ASITooMuchRedirectionErrorType = 9,
  55. ASIUnhandledExceptionError = 10,
  56. ASICompressionError = 11
  57. } ASINetworkErrorType;
  58. // The error domain that all errors generated by ASIHTTPRequest use
  59. extern NSString* const NetworkRequestErrorDomain;
  60. // You can use this number to throttle upload and download bandwidth in iPhone OS apps send or receive a large amount of data
  61. // This may help apps that might otherwise be rejected for inclusion into the app store for using excessive bandwidth
  62. // This number is not official, as far as I know there is no officially documented bandwidth limit
  63. extern unsigned long const ASIWWANBandwidthThrottleAmount;
  64. #if NS_BLOCKS_AVAILABLE
  65. typedef void (^ASIBasicBlock)(void);
  66. typedef void (^ASIHeadersBlock)(NSDictionary *responseHeaders);
  67. typedef void (^ASISizeBlock)(long long size);
  68. typedef void (^ASIProgressBlock)(unsigned long long size, unsigned long long total);
  69. typedef void (^ASIDataBlock)(NSData *data);
  70. #endif
  71. @interface ASIHTTPRequest : NSOperation <NSCopying> {
  72. // The url for this operation, should include GET params in the query string where appropriate
  73. NSURL *url;
  74. // Will always contain the original url used for making the request (the value of url can change when a request is redirected)
  75. NSURL *originalURL;
  76. // Temporarily stores the url we are about to redirect to. Will be nil again when we do redirect
  77. NSURL *redirectURL;
  78. // The delegate - will be notified of various changes in state via the ASIHTTPRequestDelegate protocol
  79. id <ASIHTTPRequestDelegate> delegate;
  80. // Another delegate that is also notified of request status changes and progress updates
  81. // Generally, you won't use this directly, but ASINetworkQueue sets itself as the queue so it can proxy updates to its own delegates
  82. // NOTE: WILL BE RETAINED BY THE REQUEST
  83. id <ASIHTTPRequestDelegate, ASIProgressDelegate> queue;
  84. // HTTP method to use (eg: GET / POST / PUT / DELETE / HEAD etc). Defaults to GET
  85. NSString *requestMethod;
  86. // Request body - only used when the whole body is stored in memory (shouldStreamPostDataFromDisk is false)
  87. NSMutableData *postBody;
  88. // gzipped request body used when shouldCompressRequestBody is YES
  89. NSData *compressedPostBody;
  90. // When true, post body will be streamed from a file on disk, rather than loaded into memory at once (useful for large uploads)
  91. // Automatically set to true in ASIFormDataRequests when using setFile:forKey:
  92. BOOL shouldStreamPostDataFromDisk;
  93. // Path to file used to store post body (when shouldStreamPostDataFromDisk is true)
  94. // You can set this yourself - useful if you want to PUT a file from local disk
  95. NSString *postBodyFilePath;
  96. // Path to a temporary file used to store a deflated post body (when shouldCompressPostBody is YES)
  97. NSString *compressedPostBodyFilePath;
  98. // Set to true when ASIHTTPRequest automatically created a temporary file containing the request body (when true, the file at postBodyFilePath will be deleted at the end of the request)
  99. BOOL didCreateTemporaryPostDataFile;
  100. // Used when writing to the post body when shouldStreamPostDataFromDisk is true (via appendPostData: or appendPostDataFromFile:)
  101. NSOutputStream *postBodyWriteStream;
  102. // Used for reading from the post body when sending the request
  103. NSInputStream *postBodyReadStream;
  104. // Dictionary for custom HTTP request headers
  105. NSMutableDictionary *requestHeaders;
  106. // Set to YES when the request header dictionary has been populated, used to prevent this happening more than once
  107. BOOL haveBuiltRequestHeaders;
  108. // Will be populated with HTTP response headers from the server
  109. NSDictionary *responseHeaders;
  110. // Can be used to manually insert cookie headers to a request, but it's more likely that sessionCookies will do this for you
  111. NSMutableArray *requestCookies;
  112. // Will be populated with cookies
  113. NSArray *responseCookies;
  114. // If use useCookiePersistence is true, network requests will present valid cookies from previous requests
  115. BOOL useCookiePersistence;
  116. // If useKeychainPersistence is true, network requests will attempt to read credentials from the keychain, and will save them in the keychain when they are successfully presented
  117. BOOL useKeychainPersistence;
  118. // If useSessionPersistence is true, network requests will save credentials and reuse for the duration of the session (until clearSession is called)
  119. BOOL useSessionPersistence;
  120. // If allowCompressedResponse is true, requests will inform the server they can accept compressed data, and will automatically decompress gzipped responses. Default is true.
  121. BOOL allowCompressedResponse;
  122. // If shouldCompressRequestBody is true, the request body will be gzipped. Default is false.
  123. // You will probably need to enable this feature on your webserver to make this work. Tested with apache only.
  124. BOOL shouldCompressRequestBody;
  125. // When downloadDestinationPath is set, the result of this request will be downloaded to the file at this location
  126. // If downloadDestinationPath is not set, download data will be stored in memory
  127. NSString *downloadDestinationPath;
  128. // The location that files will be downloaded to. Once a download is complete, files will be decompressed (if necessary) and moved to downloadDestinationPath
  129. NSString *temporaryFileDownloadPath;
  130. // If the response is gzipped and shouldWaitToInflateCompressedResponses is NO, a file will be created at this path containing the inflated response as it comes in
  131. NSString *temporaryUncompressedDataDownloadPath;
  132. // Used for writing data to a file when downloadDestinationPath is set
  133. NSOutputStream *fileDownloadOutputStream;
  134. NSOutputStream *inflatedFileDownloadOutputStream;
  135. // When the request fails or completes successfully, complete will be true
  136. BOOL complete;
  137. // external "finished" indicator, subject of KVO notifications; updates after 'complete'
  138. BOOL finished;
  139. // True if our 'cancel' selector has been called
  140. BOOL cancelled;
  141. // If an error occurs, error will contain an NSError
  142. // If error code is = ASIConnectionFailureErrorType (1, Connection failure occurred) - inspect [[error userInfo] objectForKey:NSUnderlyingErrorKey] for more information
  143. NSError *error;
  144. // Username and password used for authentication
  145. NSString *username;
  146. NSString *password;
  147. // User-Agent for this request
  148. NSString *userAgent;
  149. // Domain used for NTLM authentication
  150. NSString *domain;
  151. // Username and password used for proxy authentication
  152. NSString *proxyUsername;
  153. NSString *proxyPassword;
  154. // Domain used for NTLM proxy authentication
  155. NSString *proxyDomain;
  156. // Delegate for displaying upload progress (usually an NSProgressIndicator, but you can supply a different object and handle this yourself)
  157. id <ASIProgressDelegate> uploadProgressDelegate;
  158. // Delegate for displaying download progress (usually an NSProgressIndicator, but you can supply a different object and handle this yourself)
  159. id <ASIProgressDelegate> downloadProgressDelegate;
  160. // Whether we've seen the headers of the response yet
  161. BOOL haveExaminedHeaders;
  162. // Data we receive will be stored here. Data may be compressed unless allowCompressedResponse is false - you should use [request responseData] instead in most cases
  163. NSMutableData *rawResponseData;
  164. // Used for sending and receiving data
  165. CFHTTPMessageRef request;
  166. NSInputStream *readStream;
  167. // Used for authentication
  168. CFHTTPAuthenticationRef requestAuthentication;
  169. NSDictionary *requestCredentials;
  170. // Used during NTLM authentication
  171. int authenticationRetryCount;
  172. // Authentication scheme (Basic, Digest, NTLM)
  173. // If you are using Basic authentication and want to force ASIHTTPRequest to send an authorization header without waiting for a 401, you must set this to (NSString *)kCFHTTPAuthenticationSchemeBasic
  174. NSString *authenticationScheme;
  175. // Realm for authentication when credentials are required
  176. NSString *authenticationRealm;
  177. // When YES, ASIHTTPRequest will present a dialog allowing users to enter credentials when no-matching credentials were found for a server that requires authentication
  178. // The dialog will not be shown if your delegate responds to authenticationNeededForRequest:
  179. // Default is NO.
  180. BOOL shouldPresentAuthenticationDialog;
  181. // When YES, ASIHTTPRequest will present a dialog allowing users to enter credentials when no-matching credentials were found for a proxy server that requires authentication
  182. // The dialog will not be shown if your delegate responds to proxyAuthenticationNeededForRequest:
  183. // Default is YES (basically, because most people won't want the hassle of adding support for authenticating proxies to their apps)
  184. BOOL shouldPresentProxyAuthenticationDialog;
  185. // Used for proxy authentication
  186. CFHTTPAuthenticationRef proxyAuthentication;
  187. NSDictionary *proxyCredentials;
  188. // Used during authentication with an NTLM proxy
  189. int proxyAuthenticationRetryCount;
  190. // Authentication scheme for the proxy (Basic, Digest, NTLM)
  191. NSString *proxyAuthenticationScheme;
  192. // Realm for proxy authentication when credentials are required
  193. NSString *proxyAuthenticationRealm;
  194. // HTTP status code, eg: 200 = OK, 404 = Not found etc
  195. int responseStatusCode;
  196. // Description of the HTTP status code
  197. NSString *responseStatusMessage;
  198. // Size of the response
  199. unsigned long long contentLength;
  200. // Size of the partially downloaded content
  201. unsigned long long partialDownloadSize;
  202. // Size of the POST payload
  203. unsigned long long postLength;
  204. // The total amount of downloaded data
  205. unsigned long long totalBytesRead;
  206. // The total amount of uploaded data
  207. unsigned long long totalBytesSent;
  208. // Last amount of data read (used for incrementing progress)
  209. unsigned long long lastBytesRead;
  210. // Last amount of data sent (used for incrementing progress)
  211. unsigned long long lastBytesSent;
  212. // This lock prevents the operation from being cancelled at an inopportune moment
  213. NSRecursiveLock *cancelledLock;
  214. // Called on the delegate (if implemented) when the request starts. Default is requestStarted:
  215. SEL didStartSelector;
  216. // Called on the delegate (if implemented) when the request receives response headers. Default is request:didReceiveResponseHeaders:
  217. SEL didReceiveResponseHeadersSelector;
  218. // Called on the delegate (if implemented) when the request receives a Location header and shouldRedirect is YES
  219. // The delegate can then change the url if needed, and can restart the request by calling [request redirectToURL:], or simply cancel it
  220. SEL willRedirectSelector;
  221. // Called on the delegate (if implemented) when the request completes successfully. Default is requestFinished:
  222. SEL didFinishSelector;
  223. // Called on the delegate (if implemented) when the request fails. Default is requestFailed:
  224. SEL didFailSelector;
  225. // Called on the delegate (if implemented) when the request receives data. Default is request:didReceiveData:
  226. // If you set this and implement the method in your delegate, you must handle the data yourself - ASIHTTPRequest will not populate responseData or write the data to downloadDestinationPath
  227. SEL didReceiveDataSelector;
  228. // Used for recording when something last happened during the request, we will compare this value with the current date to time out requests when appropriate
  229. NSDate *lastActivityTime;
  230. // Number of seconds to wait before timing out - default is 10
  231. NSTimeInterval timeOutSeconds;
  232. // Will be YES when a HEAD request will handle the content-length before this request starts
  233. BOOL shouldResetUploadProgress;
  234. BOOL shouldResetDownloadProgress;
  235. // Used by HEAD requests when showAccurateProgress is YES to preset the content-length for this request
  236. ASIHTTPRequest *mainRequest;
  237. // When NO, this request will only update the progress indicator when it completes
  238. // When YES, this request will update the progress indicator according to how much data it has received so far
  239. // The default for requests is YES
  240. // Also see the comments in ASINetworkQueue.h
  241. BOOL showAccurateProgress;
  242. // Used to ensure the progress indicator is only incremented once when showAccurateProgress = NO
  243. BOOL updatedProgress;
  244. // Prevents the body of the post being built more than once (largely for subclasses)
  245. BOOL haveBuiltPostBody;
  246. // Used internally, may reflect the size of the internal buffer used by CFNetwork
  247. // POST / PUT operations with body sizes greater than uploadBufferSize will not timeout unless more than uploadBufferSize bytes have been sent
  248. // Likely to be 32KB on iPhone 3.0, 128KB on Mac OS X Leopard and iPhone 2.2.x
  249. unsigned long long uploadBufferSize;
  250. // Text encoding for responses that do not send a Content-Type with a charset value. Defaults to NSISOLatin1StringEncoding
  251. NSStringEncoding defaultResponseEncoding;
  252. // The text encoding of the response, will be defaultResponseEncoding if the server didn't specify. Can't be set.
  253. NSStringEncoding responseEncoding;
  254. // Tells ASIHTTPRequest not to delete partial downloads, and allows it to use an existing file to resume a download. Defaults to NO.
  255. BOOL allowResumeForFileDownloads;
  256. // Custom user information associated with the request (not sent to the server)
  257. NSDictionary *userInfo;
  258. NSInteger tag;
  259. // Use HTTP 1.0 rather than 1.1 (defaults to false)
  260. BOOL useHTTPVersionOne;
  261. // When YES, requests will automatically redirect when they get a HTTP 30x header (defaults to YES)
  262. BOOL shouldRedirect;
  263. // Used internally to tell the main loop we need to stop and retry with a new url
  264. BOOL needsRedirect;
  265. // Incremented every time this request redirects. When it reaches 5, we give up
  266. int redirectCount;
  267. // When NO, requests will not check the secure certificate is valid (use for self-signed certificates during development, DO NOT USE IN PRODUCTION) Default is YES
  268. BOOL validatesSecureCertificate;
  269. // If not nil and the URL scheme is https, CFNetwork configured to supply a client certificate
  270. SecIdentityRef clientCertificateIdentity;
  271. NSArray *clientCertificates;
  272. // Details on the proxy to use - you could set these yourself, but it's probably best to let ASIHTTPRequest detect the system proxy settings
  273. NSString *proxyHost;
  274. int proxyPort;
  275. // ASIHTTPRequest will assume kCFProxyTypeHTTP if the proxy type could not be automatically determined
  276. // Set to kCFProxyTypeSOCKS if you are manually configuring a SOCKS proxy
  277. NSString *proxyType;
  278. // URL for a PAC (Proxy Auto Configuration) file. If you want to set this yourself, it's probably best if you use a local file
  279. NSURL *PACurl;
  280. // See ASIAuthenticationState values above. 0 == default == No authentication needed yet
  281. ASIAuthenticationState authenticationNeeded;
  282. // When YES, ASIHTTPRequests will present credentials from the session store for requests to the same server before being asked for them
  283. // This avoids an extra round trip for requests after authentication has succeeded, which is much for efficient for authenticated requests with large bodies, or on slower connections
  284. // Set to NO to only present credentials when explicitly asked for them
  285. // This only affects credentials stored in the session cache when useSessionPersistence is YES. Credentials from the keychain are never presented unless the server asks for them
  286. // Default is YES
  287. // For requests using Basic authentication, set authenticationScheme to (NSString *)kCFHTTPAuthenticationSchemeBasic, and credentials can be sent on the very first request when shouldPresentCredentialsBeforeChallenge is YES
  288. BOOL shouldPresentCredentialsBeforeChallenge;
  289. // YES when the request hasn't finished yet. Will still be YES even if the request isn't doing anything (eg it's waiting for delegate authentication). READ-ONLY
  290. BOOL inProgress;
  291. // Used internally to track whether the stream is scheduled on the run loop or not
  292. // Bandwidth throttling can unschedule the stream to slow things down while a request is in progress
  293. BOOL readStreamIsScheduled;
  294. // Set to allow a request to automatically retry itself on timeout
  295. // Default is zero - timeout will stop the request
  296. int numberOfTimesToRetryOnTimeout;
  297. // The number of times this request has retried (when numberOfTimesToRetryOnTimeout > 0)
  298. int retryCount;
  299. // Temporarily set to YES when a closed connection forces a retry (internally, this stops ASIHTTPRequest cleaning up a temporary post body)
  300. BOOL willRetryRequest;
  301. // When YES, requests will keep the connection to the server alive for a while to allow subsequent requests to re-use it for a substantial speed-boost
  302. // Persistent connections will not be used if the server explicitly closes the connection
  303. // Default is YES
  304. BOOL shouldAttemptPersistentConnection;
  305. // Number of seconds to keep an inactive persistent connection open on the client side
  306. // Default is 60
  307. // If we get a keep-alive header, this is this value is replaced with how long the server told us to keep the connection around
  308. // A future date is created from this and used for expiring the connection, this is stored in connectionInfo's expires value
  309. NSTimeInterval persistentConnectionTimeoutSeconds;
  310. // Set to yes when an appropriate keep-alive header is found
  311. BOOL connectionCanBeReused;
  312. // Stores information about the persistent connection that is currently in use.
  313. // It may contain:
  314. // * The id we set for a particular connection, incremented every time we want to specify that we need a new connection
  315. // * The date that connection should expire
  316. // * A host, port and scheme for the connection. These are used to determine whether that connection can be reused by a subsequent request (all must match the new request)
  317. // * An id for the request that is currently using the connection. This is used for determining if a connection is available or not (we store a number rather than a reference to the request so we don't need to hang onto a request until the connection expires)
  318. // * A reference to the stream that is currently using the connection. This is necessary because we need to keep the old stream open until we've opened a new one.
  319. // The stream will be closed + released either when another request comes to use the connection, or when the timer fires to tell the connection to expire
  320. NSMutableDictionary *connectionInfo;
  321. // When set to YES, 301 and 302 automatic redirects will use the original method and and body, according to the HTTP 1.1 standard
  322. // Default is NO (to follow the behaviour of most browsers)
  323. BOOL shouldUseRFC2616RedirectBehaviour;
  324. // Used internally to record when a request has finished downloading data
  325. BOOL downloadComplete;
  326. // An ID that uniquely identifies this request - primarily used for debugging persistent connections
  327. NSNumber *requestID;
  328. // Will be ASIHTTPRequestRunLoopMode for synchronous requests, NSDefaultRunLoopMode for all other requests
  329. NSString *runLoopMode;
  330. // This timer checks up on the request every 0.25 seconds, and updates progress
  331. NSTimer *statusTimer;
  332. // The download cache that will be used for this request (use [ASIHTTPRequest setDefaultCache:cache] to configure a default cache
  333. id <ASICacheDelegate> downloadCache;
  334. // The cache policy that will be used for this request - See ASICacheDelegate.h for possible values
  335. ASICachePolicy cachePolicy;
  336. // The cache storage policy that will be used for this request - See ASICacheDelegate.h for possible values
  337. ASICacheStoragePolicy cacheStoragePolicy;
  338. // Will be true when the response was pulled from the cache rather than downloaded
  339. BOOL didUseCachedResponse;
  340. // Set secondsToCache to use a custom time interval for expiring the response when it is stored in a cache
  341. NSTimeInterval secondsToCache;
  342. #if TARGET_OS_IPHONE && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_4_0
  343. BOOL shouldContinueWhenAppEntersBackground;
  344. UIBackgroundTaskIdentifier backgroundTask;
  345. #endif
  346. // When downloading a gzipped response, the request will use this helper object to inflate the response
  347. ASIDataDecompressor *dataDecompressor;
  348. // Controls how responses with a gzipped encoding are inflated (decompressed)
  349. // When set to YES (This is the default):
  350. // * gzipped responses for requests without a downloadDestinationPath will be inflated only when [request responseData] / [request responseString] is called
  351. // * gzipped responses for requests with a downloadDestinationPath set will be inflated only when the request completes
  352. //
  353. // When set to NO
  354. // All requests will inflate the response as it comes in
  355. // * If the request has no downloadDestinationPath set, the raw (compressed) response is discarded and rawResponseData will contain the decompressed response
  356. // * If the request has a downloadDestinationPath, the raw response will be stored in temporaryFileDownloadPath as normal, the inflated response will be stored in temporaryUncompressedDataDownloadPath
  357. // Once the request completes successfully, the contents of temporaryUncompressedDataDownloadPath are moved into downloadDestinationPath
  358. //
  359. // Setting this to NO may be especially useful for users using ASIHTTPRequest in conjunction with a streaming parser, as it will allow partial gzipped responses to be inflated and passed on to the parser while the request is still running
  360. BOOL shouldWaitToInflateCompressedResponses;
  361. // Will be YES if this is a request created behind the scenes to download a PAC file - these requests do not attempt to configure their own proxies
  362. BOOL isPACFileRequest;
  363. // Used for downloading PAC files from http / https webservers
  364. ASIHTTPRequest *PACFileRequest;
  365. // Used for asynchronously reading PAC files from file:// URLs
  366. NSInputStream *PACFileReadStream;
  367. // Used for storing PAC data from file URLs as it is downloaded
  368. NSMutableData *PACFileData;
  369. // Set to YES in startSynchronous. Currently used by proxy detection to download PAC files synchronously when appropriate
  370. BOOL isSynchronous;
  371. #if NS_BLOCKS_AVAILABLE
  372. //block to execute when request starts
  373. ASIBasicBlock startedBlock;
  374. //block to execute when headers are received
  375. ASIHeadersBlock headersReceivedBlock;
  376. //block to execute when request completes successfully
  377. ASIBasicBlock completionBlock;
  378. //block to execute when request fails
  379. ASIBasicBlock failureBlock;
  380. //block for when bytes are received
  381. ASIProgressBlock bytesReceivedBlock;
  382. //block for when bytes are sent
  383. ASIProgressBlock bytesSentBlock;
  384. //block for when download size is incremented
  385. ASISizeBlock downloadSizeIncrementedBlock;
  386. //block for when upload size is incremented
  387. ASISizeBlock uploadSizeIncrementedBlock;
  388. //block for handling raw bytes received
  389. ASIDataBlock dataReceivedBlock;
  390. //block for handling authentication
  391. ASIBasicBlock authenticationNeededBlock;
  392. //block for handling proxy authentication
  393. ASIBasicBlock proxyAuthenticationNeededBlock;
  394. //block for handling redirections, if you want to
  395. ASIBasicBlock requestRedirectedBlock;
  396. #endif
  397. }
  398. #pragma mark init / dealloc
  399. // Should be an HTTP or HTTPS url, may include username and password if appropriate
  400. - (id)initWithURL:(NSURL *)newURL;
  401. // Convenience constructor
  402. + (id)requestWithURL:(NSURL *)newURL;
  403. + (id)requestWithURL:(NSURL *)newURL usingCache:(id <ASICacheDelegate>)cache;
  404. + (id)requestWithURL:(NSURL *)newURL usingCache:(id <ASICacheDelegate>)cache andCachePolicy:(ASICachePolicy)policy;
  405. #if NS_BLOCKS_AVAILABLE
  406. - (void)setStartedBlock:(ASIBasicBlock)aStartedBlock;
  407. - (void)setHeadersReceivedBlock:(ASIHeadersBlock)aReceivedBlock;
  408. - (void)setCompletionBlock:(ASIBasicBlock)aCompletionBlock;
  409. - (void)setFailedBlock:(ASIBasicBlock)aFailedBlock;
  410. - (void)setBytesReceivedBlock:(ASIProgressBlock)aBytesReceivedBlock;
  411. - (void)setBytesSentBlock:(ASIProgressBlock)aBytesSentBlock;
  412. - (void)setDownloadSizeIncrementedBlock:(ASISizeBlock) aDownloadSizeIncrementedBlock;
  413. - (void)setUploadSizeIncrementedBlock:(ASISizeBlock) anUploadSizeIncrementedBlock;
  414. - (void)setDataReceivedBlock:(ASIDataBlock)aReceivedBlock;
  415. - (void)setAuthenticationNeededBlock:(ASIBasicBlock)anAuthenticationBlock;
  416. - (void)setProxyAuthenticationNeededBlock:(ASIBasicBlock)aProxyAuthenticationBlock;
  417. - (void)setRequestRedirectedBlock:(ASIBasicBlock)aRedirectBlock;
  418. #endif
  419. #pragma mark setup request
  420. // Add a custom header to the request
  421. - (void)addRequestHeader:(NSString *)header value:(NSString *)value;
  422. // Called during buildRequestHeaders and after a redirect to create a cookie header from request cookies and the global store
  423. - (void)applyCookieHeader;
  424. // Populate the request headers dictionary. Called before a request is started, or by a HEAD request that needs to borrow them
  425. - (void)buildRequestHeaders;
  426. // Used to apply authorization header to a request before it is sent (when shouldPresentCredentialsBeforeChallenge is YES)
  427. - (void)applyAuthorizationHeader;
  428. // Create the post body
  429. - (void)buildPostBody;
  430. // Called to add data to the post body. Will append to postBody when shouldStreamPostDataFromDisk is false, or write to postBodyWriteStream when true
  431. - (void)appendPostData:(NSData *)data;
  432. - (void)appendPostDataFromFile:(NSString *)file;
  433. #pragma mark get information about this request
  434. // Returns the contents of the result as an NSString (not appropriate for binary data - used responseData instead)
  435. - (NSString *)responseString;
  436. // Response data, automatically uncompressed where appropriate
  437. - (NSData *)responseData;
  438. // Returns true if the response was gzip compressed
  439. - (BOOL)isResponseCompressed;
  440. #pragma mark running a request
  441. // Run a request synchronously, and return control when the request completes or fails
  442. - (void)startSynchronous;
  443. // Run request in the background
  444. - (void)startAsynchronous;
  445. // Clears all delegates and blocks, then cancels the request
  446. - (void)clearDelegatesAndCancel;
  447. #pragma mark HEAD request
  448. // Used by ASINetworkQueue to create a HEAD request appropriate for this request with the same headers (though you can use it yourself)
  449. - (ASIHTTPRequest *)HEADRequest;
  450. #pragma mark upload/download progress
  451. // Called approximately every 0.25 seconds to update the progress delegates
  452. - (void)updateProgressIndicators;
  453. // Updates upload progress (notifies the queue and/or uploadProgressDelegate of this request)
  454. - (void)updateUploadProgress;
  455. // Updates download progress (notifies the queue and/or uploadProgressDelegate of this request)
  456. - (void)updateDownloadProgress;
  457. // Called when authorisation is needed, as we only find out we don't have permission to something when the upload is complete
  458. - (void)removeUploadProgressSoFar;
  459. // Called when we get a content-length header and shouldResetDownloadProgress is true
  460. - (void)incrementDownloadSizeBy:(long long)length;
  461. // Called when a request starts and shouldResetUploadProgress is true
  462. // Also called (with a negative length) to remove the size of the underlying buffer used for uploading
  463. - (void)incrementUploadSizeBy:(long long)length;
  464. // Helper method for interacting with progress indicators to abstract the details of different APIS (NSProgressIndicator and UIProgressView)
  465. + (void)updateProgressIndicator:(id *)indicator withProgress:(unsigned long long)progress ofTotal:(unsigned long long)total;
  466. // Helper method used for performing invocations on the main thread (used for progress)
  467. + (void)performSelector:(SEL)selector onTarget:(id *)target withObject:(id)object amount:(void *)amount callerToRetain:(id)caller;
  468. #pragma mark talking to delegates
  469. // Called when a request starts, lets the delegate know via didStartSelector
  470. - (void)requestStarted;
  471. // Called when a request receives response headers, lets the delegate know via didReceiveResponseHeadersSelector
  472. - (void)requestReceivedResponseHeaders:(NSDictionary *)newHeaders;
  473. // Called when a request completes successfully, lets the delegate know via didFinishSelector
  474. - (void)requestFinished;
  475. // Called when a request fails, and lets the delegate know via didFailSelector
  476. - (void)failWithError:(NSError *)theError;
  477. // Called to retry our request when our persistent connection is closed
  478. // Returns YES if we haven't already retried, and connection will be restarted
  479. // Otherwise, returns NO, and nothing will happen
  480. - (BOOL)retryUsingNewConnection;
  481. // Can be called by delegates from inside their willRedirectSelector implementations to restart the request with a new url
  482. - (void)redirectToURL:(NSURL *)newURL;
  483. #pragma mark parsing HTTP response headers
  484. // Reads the response headers to find the content length, encoding, cookies for the session
  485. // Also initiates request redirection when shouldRedirect is true
  486. // And works out if HTTP auth is required
  487. - (void)readResponseHeaders;
  488. // Attempts to set the correct encoding by looking at the Content-Type header, if this is one
  489. - (void)parseStringEncodingFromHeaders;
  490. + (void)parseMimeType:(NSString **)mimeType andResponseEncoding:(NSStringEncoding *)stringEncoding fromContentType:(NSString *)contentType;
  491. #pragma mark http authentication stuff
  492. // Apply credentials to this request
  493. - (BOOL)applyCredentials:(NSDictionary *)newCredentials;
  494. - (BOOL)applyProxyCredentials:(NSDictionary *)newCredentials;
  495. // Attempt to obtain credentials for this request from the URL, username and password or keychain
  496. - (NSMutableDictionary *)findCredentials;
  497. - (NSMutableDictionary *)findProxyCredentials;
  498. // Unlock (unpause) the request thread so it can resume the request
  499. // Should be called by delegates when they have populated the authentication information after an authentication challenge
  500. - (void)retryUsingSuppliedCredentials;
  501. // Should be called by delegates when they wish to cancel authentication and stop
  502. - (void)cancelAuthentication;
  503. // Apply authentication information and resume the request after an authentication challenge
  504. - (void)attemptToApplyCredentialsAndResume;
  505. - (void)attemptToApplyProxyCredentialsAndResume;
  506. // Attempt to show the built-in authentication dialog, returns YES if credentials were supplied, NO if user cancelled dialog / dialog is disabled / running on main thread
  507. // Currently only used on iPhone OS
  508. - (BOOL)showProxyAuthenticationDialog;
  509. - (BOOL)showAuthenticationDialog;
  510. // Construct a basic authentication header from the username and password supplied, and add it to the request headers
  511. // Used when shouldPresentCredentialsBeforeChallenge is YES
  512. - (void)addBasicAuthenticationHeaderWithUsername:(NSString *)theUsername andPassword:(NSString *)thePassword;
  513. #pragma mark stream status handlers
  514. // CFnetwork event handlers
  515. - (void)handleNetworkEvent:(CFStreamEventType)type;
  516. - (void)handleBytesAvailable;
  517. - (void)handleStreamComplete;
  518. - (void)handleStreamError;
  519. #pragma mark cleanup
  520. // Cleans up and lets the queue know this operation is finished.
  521. // Appears in this header for subclassing only, do not call this method from outside your request!
  522. - (void)markAsFinished;
  523. // Cleans up temporary files. There's normally no reason to call these yourself, they are called automatically when a request completes or fails
  524. // Clean up the temporary file used to store the downloaded data when it comes in (if downloadDestinationPath is set)
  525. - (BOOL)removeTemporaryDownloadFile;
  526. // Clean up the temporary file used to store data that is inflated (decompressed) as it comes in
  527. - (BOOL)removeTemporaryUncompressedDownloadFile;
  528. // Clean up the temporary file used to store the request body (when shouldStreamPostDataFromDisk is YES)
  529. - (BOOL)removeTemporaryUploadFile;
  530. // Clean up the temporary file used to store a deflated (compressed) request body when shouldStreamPostDataFromDisk is YES
  531. - (BOOL)removeTemporaryCompressedUploadFile;
  532. // Remove a file on disk, returning NO and populating the passed error pointer if it fails
  533. + (BOOL)removeFileAtPath:(NSString *)path error:(NSError **)err;
  534. #pragma mark persistent connections
  535. // Get the ID of the connection this request used (only really useful in tests and debugging)
  536. - (NSNumber *)connectionID;
  537. // Called automatically when a request is started to clean up any persistent connections that have expired
  538. + (void)expirePersistentConnections;
  539. #pragma mark default time out
  540. + (NSTimeInterval)defaultTimeOutSeconds;
  541. + (void)setDefaultTimeOutSeconds:(NSTimeInterval)newTimeOutSeconds;
  542. #pragma mark client certificate
  543. - (void)setClientCertificateIdentity:(SecIdentityRef)anIdentity;
  544. #pragma mark session credentials
  545. + (NSMutableArray *)sessionProxyCredentialsStore;
  546. + (NSMutableArray *)sessionCredentialsStore;
  547. + (void)storeProxyAuthenticationCredentialsInSessionStore:(NSDictionary *)credentials;
  548. + (void)storeAuthenticationCredentialsInSessionStore:(NSDictionary *)credentials;
  549. + (void)removeProxyAuthenticationCredentialsFromSessionStore:(NSDictionary *)credentials;
  550. + (void)removeAuthenticationCredentialsFromSessionStore:(NSDictionary *)credentials;
  551. - (NSDictionary *)findSessionProxyAuthenticationCredentials;
  552. - (NSDictionary *)findSessionAuthenticationCredentials;
  553. #pragma mark keychain storage
  554. // Save credentials for this request to the keychain
  555. - (void)saveCredentialsToKeychain:(NSDictionary *)newCredentials;
  556. // Save credentials to the keychain
  557. + (void)saveCredentials:(NSURLCredential *)credentials forHost:(NSString *)host port:(int)port protocol:(NSString *)protocol realm:(NSString *)realm;
  558. + (void)saveCredentials:(NSURLCredential *)credentials forProxy:(NSString *)host port:(int)port realm:(NSString *)realm;
  559. // Return credentials from the keychain
  560. + (NSURLCredential *)savedCredentialsForHost:(NSString *)host port:(int)port protocol:(NSString *)protocol realm:(NSString *)realm;
  561. + (NSURLCredential *)savedCredentialsForProxy:(NSString *)host port:(int)port protocol:(NSString *)protocol realm:(NSString *)realm;
  562. // Remove credentials from the keychain
  563. + (void)removeCredentialsForHost:(NSString *)host port:(int)port protocol:(NSString *)protocol realm:(NSString *)realm;
  564. + (void)removeCredentialsForProxy:(NSString *)host port:(int)port realm:(NSString *)realm;
  565. // We keep track of any cookies we accept, so that we can remove them from the persistent store later
  566. + (void)setSessionCookies:(NSMutableArray *)newSessionCookies;
  567. + (NSMutableArray *)sessionCookies;
  568. // Adds a cookie to our list of cookies we've accepted, checking first for an old version of the same cookie and removing that
  569. + (void)addSessionCookie:(NSHTTPCookie *)newCookie;
  570. // Dump all session data (authentication and cookies)
  571. + (void)clearSession;
  572. #pragma mark get user agent
  573. // Will be used as a user agent if requests do not specify a custom user agent
  574. // Is only used when you have specified a Bundle Display Name (CFDisplayBundleName) or Bundle Name (CFBundleName) in your plist
  575. + (NSString *)defaultUserAgentString;
  576. + (void)setDefaultUserAgentString:(NSString *)agent;
  577. #pragma mark mime-type detection
  578. // Return the mime type for a file
  579. + (NSString *)mimeTypeForFileAtPath:(NSString *)path;
  580. #pragma mark bandwidth measurement / throttling
  581. // The maximum number of bytes ALL requests can send / receive in a second
  582. // This is a rough figure. The actual amount used will be slightly more, this does not include HTTP headers
  583. + (unsigned long)maxBandwidthPerSecond;
  584. + (void)setMaxBandwidthPerSecond:(unsigned long)bytes;
  585. // Get a rough average (for the last 5 seconds) of how much bandwidth is being used, in bytes
  586. + (unsigned long)averageBandwidthUsedPerSecond;
  587. - (void)performThrottling;
  588. // Will return YES is bandwidth throttling is currently in use
  589. + (BOOL)isBandwidthThrottled;
  590. // Used internally to record bandwidth use, and by ASIInputStreams when uploading. It's probably best if you don't mess with this.
  591. + (void)incrementBandwidthUsedInLastSecond:(unsigned long)bytes;
  592. // On iPhone, ASIHTTPRequest can automatically turn throttling on and off as the connection type changes between WWAN and WiFi
  593. #if TARGET_OS_IPHONE
  594. // Set to YES to automatically turn on throttling when WWAN is connected, and automatically turn it off when it isn't
  595. + (void)setShouldThrottleBandwidthForWWAN:(BOOL)throttle;
  596. // Turns on throttling automatically when WWAN is connected using a custom limit, and turns it off automatically when it isn't
  597. + (void)throttleBandwidthForWWANUsingLimit:(unsigned long)limit;
  598. #pragma mark reachability
  599. // Returns YES when an iPhone OS device is connected via WWAN, false when connected via WIFI or not connected
  600. + (BOOL)isNetworkReachableViaWWAN;
  601. #endif
  602. #pragma mark queue
  603. // Returns the shared queue
  604. + (NSOperationQueue *)sharedQueue;
  605. #pragma mark cache
  606. + (void)setDefaultCache:(id <ASICacheDelegate>)cache;
  607. + (id <ASICacheDelegate>)defaultCache;
  608. // Returns the maximum amount of data we can read as part of the current measurement period, and sleeps this thread if our allowance is used up
  609. + (unsigned long)maxUploadReadLength;
  610. #pragma mark network activity
  611. + (BOOL)isNetworkInUse;
  612. + (void)setShouldUpdateNetworkActivityIndicator:(BOOL)shouldUpdate;
  613. // Shows the network activity spinner thing on iOS. You may wish to override this to do something else in Mac projects
  614. + (void)showNetworkActivityIndicator;
  615. // Hides the network activity spinner thing on iOS
  616. + (void)hideNetworkActivityIndicator;
  617. #pragma mark miscellany
  618. // Used for generating Authorization header when using basic authentication when shouldPresentCredentialsBeforeChallenge is true
  619. // And also by ASIS3Request
  620. + (NSString *)base64forData:(NSData *)theData;
  621. // Returns the expiration date for the request.
  622. // Calculated from the Expires response header property, unless maxAge is non-zero or
  623. // there exists a non-zero max-age property in the Cache-Control response header.
  624. + (NSDate *)expiryDateForRequest:(ASIHTTPRequest *)request maxAge:(NSTimeInterval)maxAge;
  625. // Returns a date from a string in RFC1123 format
  626. + (NSDate *)dateFromRFC1123String:(NSString *)string;
  627. // Used for detecting multitasking support at runtime (for backgrounding requests)
  628. #if TARGET_OS_IPHONE
  629. + (BOOL)isMultitaskingSupported;
  630. #endif
  631. #pragma mark threading behaviour
  632. // In the default implementation, all requests run in a single background thread
  633. // Advanced users only: Override this method in a subclass for a different threading behaviour
  634. // Eg: return [NSThread mainThread] to run all requests in the main thread
  635. // Alternatively, you can create a thread on demand, or manage a pool of threads
  636. // Threads returned by this method will need to run the runloop in default mode (eg CFRunLoopRun())
  637. // Requests will stop the runloop when they complete
  638. // If you have multiple requests sharing the thread you'll need to restart the runloop when this happens
  639. + (NSThread *)threadForRequest:(ASIHTTPRequest *)request;
  640. #pragma mark ===
  641. @property (retain) NSString *username;
  642. @property (retain) NSString *password;
  643. @property (retain) NSString *userAgent;
  644. @property (retain) NSString *domain;
  645. @property (retain) NSString *proxyUsername;
  646. @property (retain) NSString *proxyPassword;
  647. @property (retain) NSString *proxyDomain;
  648. @property (retain) NSString *proxyHost;
  649. @property (assign) int proxyPort;
  650. @property (retain) NSString *proxyType;
  651. @property (retain,setter=setURL:, nonatomic) NSURL *url;
  652. @property (retain) NSURL *originalURL;
  653. @property (assign, nonatomic) id delegate;
  654. @property (retain, nonatomic) id queue;
  655. @property (assign, nonatomic) id uploadProgressDelegate;
  656. @property (assign, nonatomic) id downloadProgressDelegate;
  657. @property (assign) BOOL useKeychainPersistence;
  658. @property (assign) BOOL useSessionPersistence;
  659. @property (retain) NSString *downloadDestinationPath;
  660. @property (retain) NSString *temporaryFileDownloadPath;
  661. @property (retain) NSString *temporaryUncompressedDataDownloadPath;
  662. @property (assign) SEL didStartSelector;
  663. @property (assign) SEL didReceiveResponseHeadersSelector;
  664. @property (assign) SEL willRedirectSelector;
  665. @property (assign) SEL didFinishSelector;
  666. @property (assign) SEL didFailSelector;
  667. @property (assign) SEL didReceiveDataSelector;
  668. @property (retain,readonly) NSString *authenticationRealm;
  669. @property (retain,readonly) NSString *proxyAuthenticationRealm;
  670. @property (retain) NSError *error;
  671. @property (assign,readonly) BOOL complete;
  672. @property (retain) NSDictionary *responseHeaders;
  673. @property (retain) NSMutableDictionary *requestHeaders;
  674. @property (retain) NSMutableArray *requestCookies;
  675. @property (retain,readonly) NSArray *responseCookies;
  676. @property (assign) BOOL useCookiePersistence;
  677. @property (retain) NSDictionary *requestCredentials;
  678. @property (retain) NSDictionary *proxyCredentials;
  679. @property (assign,readonly) int responseStatusCode;
  680. @property (retain,readonly) NSString *responseStatusMessage;
  681. @property (retain) NSMutableData *rawResponseData;
  682. @property (assign) NSTimeInterval timeOutSeconds;
  683. @property (retain, nonatomic) NSString *requestMethod;
  684. @property (retain) NSMutableData *postBody;
  685. @property (assign) unsigned long long contentLength;
  686. @property (assign) unsigned long long postLength;
  687. @property (assign) BOOL shouldResetDownloadProgress;
  688. @property (assign) BOOL shouldResetUploadProgress;
  689. @property (assign) ASIHTTPRequest *mainRequest;
  690. @property (assign) BOOL showAccurateProgress;
  691. @property (assign) unsigned long long totalBytesRead;
  692. @property (assign) unsigned long long totalBytesSent;
  693. @property (assign) NSStringEncoding defaultResponseEncoding;
  694. @property (assign) NSStringEncoding responseEncoding;
  695. @property (assign) BOOL allowCompressedResponse;
  696. @property (assign) BOOL allowResumeForFileDownloads;
  697. @property (retain) NSDictionary *userInfo;
  698. @property (assign) NSInteger tag;
  699. @property (retain) NSString *postBodyFilePath;
  700. @property (assign) BOOL shouldStreamPostDataFromDisk;
  701. @property (assign) BOOL didCreateTemporaryPostDataFile;
  702. @property (assign) BOOL useHTTPVersionOne;
  703. @property (assign, readonly) unsigned long long partialDownloadSize;
  704. @property (assign) BOOL shouldRedirect;
  705. @property (assign) BOOL validatesSecureCertificate;
  706. @property (assign) BOOL shouldCompressRequestBody;
  707. @property (retain) NSURL *PACurl;
  708. @property (retain) NSString *authenticationScheme;
  709. @property (retain) NSString *proxyAuthenticationScheme;
  710. @property (assign) BOOL shouldPresentAuthenticationDialog;
  711. @property (assign) BOOL shouldPresentProxyAuthenticationDialog;
  712. @property (assign, readonly) ASIAuthenticationState authenticationNeeded;
  713. @property (assign) BOOL shouldPresentCredentialsBeforeChallenge;
  714. @property (assign, readonly) int authenticationRetryCount;
  715. @property (assign, readonly) int proxyAuthenticationRetryCount;
  716. @property (assign) BOOL haveBuiltRequestHeaders;
  717. @property (assign, nonatomic) BOOL haveBuiltPostBody;
  718. @property (assign, readonly) BOOL inProgress;
  719. @property (assign) int numberOfTimesToRetryOnTimeout;
  720. @property (assign, readonly) int retryCount;
  721. @property (assign) BOOL shouldAttemptPersistentConnection;
  722. @property (assign) NSTimeInterval persistentConnectionTimeoutSeconds;
  723. @property (assign) BOOL shouldUseRFC2616RedirectBehaviour;
  724. @property (assign, readonly) BOOL connectionCanBeReused;
  725. @property (retain, readonly) NSNumber *requestID;
  726. @property (assign) id <ASICacheDelegate> downloadCache;
  727. @property (assign) ASICachePolicy cachePolicy;
  728. @property (assign) ASICacheStoragePolicy cacheStoragePolicy;
  729. @property (assign, readonly) BOOL didUseCachedResponse;
  730. @property (assign) NSTimeInterval secondsToCache;
  731. @property (retain) NSArray *clientCertificates;
  732. #if TARGET_OS_IPHONE && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_4_0
  733. @property (assign) BOOL shouldContinueWhenAppEntersBackground;
  734. #endif
  735. @property (retain) ASIDataDecompressor *dataDecompressor;
  736. @property (assign) BOOL shouldWaitToInflateCompressedResponses;
  737. @end