4 // Created by Ben Copsey on 04/10/2007.
5 // Copyright 2007-2010 All-Seeing Interactive. All rights reserved.
7 // A guide to the main features is available at:
8 // http://allseeing-i.com/ASIHTTPRequest
10 // Portions are based on the ImageClient example from Apple:
11 // See: http://developer.apple.com/samplecode/ImageClient/listing37.html
13 #import <Foundation/Foundation.h>
15 #import <CFNetwork/CFNetwork.h>
19 #import "ASIHTTPRequestConfig.h"
20 #import "ASIHTTPRequestDelegate.h"
21 #import "ASIProgressDelegate.h"
22 #import "ASICacheDelegate.h"
24 @class ASIDataDecompressor;
26 extern NSString *ASIHTTPRequestVersion;
28 // Make targeting different platforms more reliable
29 // See: http://www.blumtnwerx.com/blog/2009/06/cross-sdk-code-hygiene-in-xcode/
31 #define __IPHONE_3_2 30200
34 #define __IPHONE_4_0 40000
37 #define __MAC_10_5 1050
40 #define __MAC_10_6 1060
43 typedef enum _ASIAuthenticationState {
44 ASINoAuthenticationNeededYet = 0,
45 ASIHTTPAuthenticationNeeded = 1,
46 ASIProxyAuthenticationNeeded = 2
47 } ASIAuthenticationState;
49 typedef enum _ASINetworkErrorType {
50 ASIConnectionFailureErrorType = 1,
51 ASIRequestTimedOutErrorType = 2,
52 ASIAuthenticationErrorType = 3,
53 ASIRequestCancelledErrorType = 4,
54 ASIUnableToCreateRequestErrorType = 5,
55 ASIInternalErrorWhileBuildingRequestType = 6,
56 ASIInternalErrorWhileApplyingCredentialsType = 7,
57 ASIFileManagementError = 8,
58 ASITooMuchRedirectionErrorType = 9,
59 ASIUnhandledExceptionError = 10,
60 ASICompressionError = 11
62 } ASINetworkErrorType;
65 // The error domain that all errors generated by ASIHTTPRequest use
66 extern NSString* const NetworkRequestErrorDomain;
68 // You can use this number to throttle upload and download bandwidth in iPhone OS apps send or receive a large amount of data
69 // This may help apps that might otherwise be rejected for inclusion into the app store for using excessive bandwidth
70 // This number is not official, as far as I know there is no officially documented bandwidth limit
71 extern unsigned long const ASIWWANBandwidthThrottleAmount;
73 #if NS_BLOCKS_AVAILABLE
74 typedef void (^ASIBasicBlock)(void);
75 typedef void (^ASIHeadersBlock)(NSDictionary *responseHeaders);
76 typedef void (^ASISizeBlock)(long long size);
77 typedef void (^ASIProgressBlock)(unsigned long long size, unsigned long long total);
78 typedef void (^ASIDataBlock)(NSData *data);
81 @interface ASIHTTPRequest : NSOperation <NSCopying> {
83 // The url for this operation, should include GET params in the query string where appropriate
86 // Will always contain the original url used for making the request (the value of url can change when a request is redirected)
89 // Temporarily stores the url we are about to redirect to. Will be nil again when we do redirect
92 // The delegate, you need to manage setting and talking to your delegate in your subclasses
93 id <ASIHTTPRequestDelegate> delegate;
95 // Another delegate that is also notified of request status changes and progress updates
96 // Generally, you won't use this directly, but ASINetworkQueue sets itself as the queue so it can proxy updates to its own delegates
97 // NOTE: WILL BE RETAINED BY THE REQUEST
98 id <ASIHTTPRequestDelegate, ASIProgressDelegate> queue;
100 // HTTP method to use (GET / POST / PUT / DELETE / HEAD). Defaults to GET
101 NSString *requestMethod;
103 // Request body - only used when the whole body is stored in memory (shouldStreamPostDataFromDisk is false)
104 NSMutableData *postBody;
106 // gzipped request body used when shouldCompressRequestBody is YES
107 NSData *compressedPostBody;
109 // When true, post body will be streamed from a file on disk, rather than loaded into memory at once (useful for large uploads)
110 // Automatically set to true in ASIFormDataRequests when using setFile:forKey:
111 BOOL shouldStreamPostDataFromDisk;
113 // Path to file used to store post body (when shouldStreamPostDataFromDisk is true)
114 // You can set this yourself - useful if you want to PUT a file from local disk
115 NSString *postBodyFilePath;
117 // Path to a temporary file used to store a deflated post body (when shouldCompressPostBody is YES)
118 NSString *compressedPostBodyFilePath;
120 // 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)
121 BOOL didCreateTemporaryPostDataFile;
123 // Used when writing to the post body when shouldStreamPostDataFromDisk is true (via appendPostData: or appendPostDataFromFile:)
124 NSOutputStream *postBodyWriteStream;
126 // Used for reading from the post body when sending the request
127 NSInputStream *postBodyReadStream;
129 // Dictionary for custom HTTP request headers
130 NSMutableDictionary *requestHeaders;
132 // Set to YES when the request header dictionary has been populated, used to prevent this happening more than once
133 BOOL haveBuiltRequestHeaders;
135 // Will be populated with HTTP response headers from the server
136 NSDictionary *responseHeaders;
138 // Can be used to manually insert cookie headers to a request, but it's more likely that sessionCookies will do this for you
139 NSMutableArray *requestCookies;
141 // Will be populated with cookies
142 NSArray *responseCookies;
144 // If use useCookiePersistence is true, network requests will present valid cookies from previous requests
145 BOOL useCookiePersistence;
147 // 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
148 BOOL useKeychainPersistence;
150 // If useSessionPersistence is true, network requests will save credentials and reuse for the duration of the session (until clearSession is called)
151 BOOL useSessionPersistence;
153 // If allowCompressedResponse is true, requests will inform the server they can accept compressed data, and will automatically decompress gzipped responses. Default is true.
154 BOOL allowCompressedResponse;
156 // If shouldCompressRequestBody is true, the request body will be gzipped. Default is false.
157 // You will probably need to enable this feature on your webserver to make this work. Tested with apache only.
158 BOOL shouldCompressRequestBody;
160 // When downloadDestinationPath is set, the result of this request will be downloaded to the file at this location
161 // If downloadDestinationPath is not set, download data will be stored in memory
162 NSString *downloadDestinationPath;
164 // The location that files will be downloaded to. Once a download is complete, files will be decompressed (if necessary) and moved to downloadDestinationPath
165 NSString *temporaryFileDownloadPath;
167 // 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
168 NSString *temporaryUncompressedDataDownloadPath;
170 // Used for writing data to a file when downloadDestinationPath is set
171 NSOutputStream *fileDownloadOutputStream;
173 NSOutputStream *inflatedFileDownloadOutputStream;
175 // When the request fails or completes successfully, complete will be true
178 // external "finished" indicator, subject of KVO notifications; updates after 'complete'
181 // True if our 'cancel' selector has been called
184 // If an error occurs, error will contain an NSError
185 // If error code is = ASIConnectionFailureErrorType (1, Connection failure occurred) - inspect [[error userInfo] objectForKey:NSUnderlyingErrorKey] for more information
188 // Username and password used for authentication
192 // Domain used for NTLM authentication
195 // Username and password used for proxy authentication
196 NSString *proxyUsername;
197 NSString *proxyPassword;
199 // Domain used for NTLM proxy authentication
200 NSString *proxyDomain;
202 // Delegate for displaying upload progress (usually an NSProgressIndicator, but you can supply a different object and handle this yourself)
203 id <ASIProgressDelegate> uploadProgressDelegate;
205 // Delegate for displaying download progress (usually an NSProgressIndicator, but you can supply a different object and handle this yourself)
206 id <ASIProgressDelegate> downloadProgressDelegate;
208 // Whether we've seen the headers of the response yet
209 BOOL haveExaminedHeaders;
211 // Data we receive will be stored here. Data may be compressed unless allowCompressedResponse is false - you should use [request responseData] instead in most cases
212 NSMutableData *rawResponseData;
214 // Used for sending and receiving data
215 CFHTTPMessageRef request;
216 NSInputStream *readStream;
218 // Used for authentication
219 CFHTTPAuthenticationRef requestAuthentication;
220 NSDictionary *requestCredentials;
222 // Used during NTLM authentication
223 int authenticationRetryCount;
225 // Authentication scheme (Basic, Digest, NTLM)
226 NSString *authenticationScheme;
228 // Realm for authentication when credentials are required
229 NSString *authenticationRealm;
231 // When YES, ASIHTTPRequest will present a dialog allowing users to enter credentials when no-matching credentials were found for a server that requires authentication
232 // The dialog will not be shown if your delegate responds to authenticationNeededForRequest:
234 BOOL shouldPresentAuthenticationDialog;
236 // 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
237 // The dialog will not be shown if your delegate responds to proxyAuthenticationNeededForRequest:
238 // Default is YES (basically, because most people won't want the hassle of adding support for authenticating proxies to their apps)
239 BOOL shouldPresentProxyAuthenticationDialog;
241 // Used for proxy authentication
242 CFHTTPAuthenticationRef proxyAuthentication;
243 NSDictionary *proxyCredentials;
245 // Used during authentication with an NTLM proxy
246 int proxyAuthenticationRetryCount;
248 // Authentication scheme for the proxy (Basic, Digest, NTLM)
249 NSString *proxyAuthenticationScheme;
251 // Realm for proxy authentication when credentials are required
252 NSString *proxyAuthenticationRealm;
254 // HTTP status code, eg: 200 = OK, 404 = Not found etc
255 int responseStatusCode;
257 // Description of the HTTP status code
258 NSString *responseStatusMessage;
260 // Size of the response
261 unsigned long long contentLength;
263 // Size of the partially downloaded content
264 unsigned long long partialDownloadSize;
266 // Size of the POST payload
267 unsigned long long postLength;
269 // The total amount of downloaded data
270 unsigned long long totalBytesRead;
272 // The total amount of uploaded data
273 unsigned long long totalBytesSent;
275 // Last amount of data read (used for incrementing progress)
276 unsigned long long lastBytesRead;
278 // Last amount of data sent (used for incrementing progress)
279 unsigned long long lastBytesSent;
281 // This lock prevents the operation from being cancelled at an inopportune moment
282 NSRecursiveLock *cancelledLock;
284 // Called on the delegate (if implemented) when the request starts. Default is requestStarted:
285 SEL didStartSelector;
287 // Called on the delegate (if implemented) when the request receives response headers. Default is requestDidReceiveResponseHeaders:
288 SEL didReceiveResponseHeadersSelector;
290 // Called on the delegate (if implemented) when the request receives a Location header and shouldRedirect is YES
291 // The delegate can then change the url if needed, and can restart the request by calling [request resume], or simply cancel it
292 SEL willRedirectSelector;
294 // Called on the delegate (if implemented) when the request completes successfully. Default is requestFinished:
295 SEL didFinishSelector;
297 // Called on the delegate (if implemented) when the request fails. Default is requestFailed:
300 // Called on the delegate (if implemented) when the request receives data. Default is request:didReceiveData:
301 // 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
302 SEL didReceiveDataSelector;
304 // 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
305 NSDate *lastActivityTime;
307 // Number of seconds to wait before timing out - default is 10
308 NSTimeInterval timeOutSeconds;
310 // Will be YES when a HEAD request will handle the content-length before this request starts
311 BOOL shouldResetUploadProgress;
312 BOOL shouldResetDownloadProgress;
314 // Used by HEAD requests when showAccurateProgress is YES to preset the content-length for this request
315 ASIHTTPRequest *mainRequest;
317 // When NO, this request will only update the progress indicator when it completes
318 // When YES, this request will update the progress indicator according to how much data it has received so far
319 // The default for requests is YES
320 // Also see the comments in ASINetworkQueue.h
321 BOOL showAccurateProgress;
323 // Used to ensure the progress indicator is only incremented once when showAccurateProgress = NO
324 BOOL updatedProgress;
326 // Prevents the body of the post being built more than once (largely for subclasses)
327 BOOL haveBuiltPostBody;
329 // Used internally, may reflect the size of the internal buffer used by CFNetwork
330 // POST / PUT operations with body sizes greater than uploadBufferSize will not timeout unless more than uploadBufferSize bytes have been sent
331 // Likely to be 32KB on iPhone 3.0, 128KB on Mac OS X Leopard and iPhone 2.2.x
332 unsigned long long uploadBufferSize;
334 // Text encoding for responses that do not send a Content-Type with a charset value. Defaults to NSISOLatin1StringEncoding
335 NSStringEncoding defaultResponseEncoding;
337 // The text encoding of the response, will be defaultResponseEncoding if the server didn't specify. Can't be set.
338 NSStringEncoding responseEncoding;
340 // Tells ASIHTTPRequest not to delete partial downloads, and allows it to use an existing file to resume a download. Defaults to NO.
341 BOOL allowResumeForFileDownloads;
343 // Custom user information associated with the request
344 NSDictionary *userInfo;
346 // Use HTTP 1.0 rather than 1.1 (defaults to false)
347 BOOL useHTTPVersionOne;
349 // When YES, requests will automatically redirect when they get a HTTP 30x header (defaults to YES)
352 // Used internally to tell the main loop we need to stop and retry with a new url
355 // Incremented every time this request redirects. When it reaches 5, we give up
358 // 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
359 BOOL validatesSecureCertificate;
361 // If not nil and the URL scheme is https, CFNetwork configured to supply a client certificate
362 SecIdentityRef clientCertificateIdentity;
363 NSArray *clientCertificates;
365 // Details on the proxy to use - you could set these yourself, but it's probably best to let ASIHTTPRequest detect the system proxy settings
369 // ASIHTTPRequest will assume kCFProxyTypeHTTP if the proxy type could not be automatically determined
370 // Set to kCFProxyTypeSOCKS if you are manually configuring a SOCKS proxy
373 // 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
376 // See ASIAuthenticationState values above. 0 == default == No authentication needed yet
377 ASIAuthenticationState authenticationNeeded;
379 // When YES, ASIHTTPRequests will present credentials from the session store for requests to the same server before being asked for them
380 // 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
381 // Set to NO to only present credentials when explicitly asked for them
382 // 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
384 BOOL shouldPresentCredentialsBeforeChallenge;
386 // 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
389 // Used internally to track whether the stream is scheduled on the run loop or not
390 // Bandwidth throttling can unschedule the stream to slow things down while a request is in progress
391 BOOL readStreamIsScheduled;
393 // Set to allow a request to automatically retry itself on timeout
394 // Default is zero - timeout will stop the request
395 int numberOfTimesToRetryOnTimeout;
397 // The number of times this request has retried (when numberOfTimesToRetryOnTimeout > 0)
400 // 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
401 // Persistent connections will not be used if the server explicitly closes the connection
403 BOOL shouldAttemptPersistentConnection;
405 // Number of seconds to keep an inactive persistent connection open on the client side
407 // 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
408 // A future date is created from this and used for expiring the connection, this is stored in connectionInfo's expires value
409 NSTimeInterval persistentConnectionTimeoutSeconds;
411 // Set to yes when an appropriate keep-alive header is found
412 BOOL connectionCanBeReused;
414 // Stores information about the persistent connection that is currently in use.
416 // * The id we set for a particular connection, incremented every time we want to specify that we need a new connection
417 // * The date that connection should expire
418 // * 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)
419 // * 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)
420 // * 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.
421 // 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
422 NSMutableDictionary *connectionInfo;
424 // When set to YES, 301 and 302 automatic redirects will use the original method and and body, according to the HTTP 1.1 standard
425 // Default is NO (to follow the behaviour of most browsers)
426 BOOL shouldUseRFC2616RedirectBehaviour;
428 // Used internally to record when a request has finished downloading data
429 BOOL downloadComplete;
431 // An ID that uniquely identifies this request - primarily used for debugging persistent connections
434 // Will be ASIHTTPRequestRunLoopMode for synchronous requests, NSDefaultRunLoopMode for all other requests
435 NSString *runLoopMode;
437 // This timer checks up on the request every 0.25 seconds, and updates progress
438 NSTimer *statusTimer;
441 // The download cache that will be used for this request (use [ASIHTTPRequest setDefaultCache:cache] to configure a default cache
442 id <ASICacheDelegate> downloadCache;
444 // The cache policy that will be used for this request - See ASICacheDelegate.h for possible values
445 ASICachePolicy cachePolicy;
447 // The cache storage policy that will be used for this request - See ASICacheDelegate.h for possible values
448 ASICacheStoragePolicy cacheStoragePolicy;
450 // Will be true when the response was pulled from the cache rather than downloaded
451 BOOL didUseCachedResponse;
453 // Set secondsToCache to use a custom time interval for expiring the response when it is stored in a cache
454 NSTimeInterval secondsToCache;
456 #if TARGET_OS_IPHONE && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_4_0
457 BOOL shouldContinueWhenAppEntersBackground;
458 //UIBackgroundTaskIdentifier backgroundTask;
463 // When downloading a gzipped response, the request will use this helper object to inflate the response
464 ASIDataDecompressor *dataDecompressor;
466 // Controls how responses with a gzipped encoding are inflated (decompressed)
467 // When set to YES (This is the default):
468 // * gzipped responses for requests without a downloadDestinationPath will be inflated only when [request responseData] / [request responseString] is called
469 // * gzipped responses for requests with a downloadDestinationPath set will be inflated only when the request completes
472 // All requests will inflate the response as it comes in
473 // * If the request has no downloadDestinationPath set, the raw (compressed) response is discarded and rawResponseData will contain the decompressed response
474 // * If the request has a downloadDestinationPath, the raw response will be stored in temporaryFileDownloadPath as normal, the inflated response will be stored in temporaryUncompressedDataDownloadPath
475 // Once the request completes successfully, the contents of temporaryUncompressedDataDownloadPath are moved into downloadDestinationPath
477 // 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
478 BOOL shouldWaitToInflateCompressedResponses;
480 #if NS_BLOCKS_AVAILABLE
481 //block to execute when request starts
482 ASIBasicBlock startedBlock;
484 //block to execute when headers are received
485 ASIHeadersBlock headersReceivedBlock;
487 //block to execute when request completes successfully
488 ASIBasicBlock completionBlock;
490 //block to execute when request fails
491 ASIBasicBlock failureBlock;
493 //block for when bytes are received
494 ASIProgressBlock bytesReceivedBlock;
496 //block for when bytes are sent
497 ASIProgressBlock bytesSentBlock;
499 //block for when download size is incremented
500 ASISizeBlock downloadSizeIncrementedBlock;
502 //block for when upload size is incremented
503 ASISizeBlock uploadSizeIncrementedBlock;
505 //block for handling raw bytes received
506 ASIDataBlock dataReceivedBlock;
508 //block for handling authentication
509 ASIBasicBlock authenticationNeededBlock;
511 //block for handling proxy authentication
512 ASIBasicBlock proxyAuthenticationNeededBlock;
514 //block for handling redirections, if you want to
515 ASIBasicBlock requestRedirectedBlock;
519 #pragma mark init / dealloc
521 // Should be an HTTP or HTTPS url, may include username and password if appropriate
522 - (id)initWithURL:(NSURL *)newURL;
524 // Convenience constructor
525 + (id)requestWithURL:(NSURL *)newURL;
527 + (id)requestWithURL:(NSURL *)newURL usingCache:(id <ASICacheDelegate>)cache;
528 + (id)requestWithURL:(NSURL *)newURL usingCache:(id <ASICacheDelegate>)cache andCachePolicy:(ASICachePolicy)policy;
530 #if NS_BLOCKS_AVAILABLE
531 - (void)setStartedBlock:(ASIBasicBlock)aStartedBlock;
532 - (void)setHeadersReceivedBlock:(ASIHeadersBlock)aReceivedBlock;
533 - (void)setCompletionBlock:(ASIBasicBlock)aCompletionBlock;
534 - (void)setFailedBlock:(ASIBasicBlock)aFailedBlock;
535 - (void)setBytesReceivedBlock:(ASIProgressBlock)aBytesReceivedBlock;
536 - (void)setBytesSentBlock:(ASIProgressBlock)aBytesSentBlock;
537 - (void)setDownloadSizeIncrementedBlock:(ASISizeBlock) aDownloadSizeIncrementedBlock;
538 - (void)setUploadSizeIncrementedBlock:(ASISizeBlock) anUploadSizeIncrementedBlock;
539 - (void)setDataReceivedBlock:(ASIDataBlock)aReceivedBlock;
540 - (void)setAuthenticationNeededBlock:(ASIBasicBlock)anAuthenticationBlock;
541 - (void)setProxyAuthenticationNeededBlock:(ASIBasicBlock)aProxyAuthenticationBlock;
542 - (void)setRequestRedirectedBlock:(ASIBasicBlock)aRedirectBlock;
545 #pragma mark setup request
547 // Add a custom header to the request
548 - (void)addRequestHeader:(NSString *)header value:(NSString *)value;
550 // Called during buildRequestHeaders and after a redirect to create a cookie header from request cookies and the global store
551 - (void)applyCookieHeader;
553 // Populate the request headers dictionary. Called before a request is started, or by a HEAD request that needs to borrow them
554 - (void)buildRequestHeaders;
556 // Used to apply authorization header to a request before it is sent (when shouldPresentCredentialsBeforeChallenge is YES)
557 - (void)applyAuthorizationHeader;
560 // Create the post body
561 - (void)buildPostBody;
563 // Called to add data to the post body. Will append to postBody when shouldStreamPostDataFromDisk is false, or write to postBodyWriteStream when true
564 - (void)appendPostData:(NSData *)data;
565 - (void)appendPostDataFromFile:(NSString *)file;
567 #pragma mark get information about this request
569 // Returns the contents of the result as an NSString (not appropriate for binary data - used responseData instead)
570 - (NSString *)responseString;
572 // Response data, automatically uncompressed where appropriate
573 - (NSData *)responseData;
575 // Returns true if the response was gzip compressed
576 - (BOOL)isResponseCompressed;
578 #pragma mark running a request
581 // Run a request synchronously, and return control when the request completes or fails
582 - (void)startSynchronous;
584 // Run request in the background
585 - (void)startAsynchronous;
587 // Clears all delegates and blocks, then cancels the request
588 - (void)clearDelegatesAndCancel;
590 #pragma mark HEAD request
592 // Used by ASINetworkQueue to create a HEAD request appropriate for this request with the same headers (though you can use it yourself)
593 - (ASIHTTPRequest *)HEADRequest;
595 #pragma mark upload/download progress
597 // Called approximately every 0.25 seconds to update the progress delegates
598 - (void)updateProgressIndicators;
600 // Updates upload progress (notifies the queue and/or uploadProgressDelegate of this request)
601 - (void)updateUploadProgress;
603 // Updates download progress (notifies the queue and/or uploadProgressDelegate of this request)
604 - (void)updateDownloadProgress;
606 // Called when authorisation is needed, as we only find out we don't have permission to something when the upload is complete
607 - (void)removeUploadProgressSoFar;
609 // Called when we get a content-length header and shouldResetDownloadProgress is true
610 - (void)incrementDownloadSizeBy:(long long)length;
612 // Called when a request starts and shouldResetUploadProgress is true
613 // Also called (with a negative length) to remove the size of the underlying buffer used for uploading
614 - (void)incrementUploadSizeBy:(long long)length;
616 // Helper method for interacting with progress indicators to abstract the details of different APIS (NSProgressIndicator and UIProgressView)
617 + (void)updateProgressIndicator:(id *)indicator withProgress:(unsigned long long)progress ofTotal:(unsigned long long)total;
619 // Helper method used for performing invocations on the main thread (used for progress)
620 + (void)performSelector:(SEL)selector onTarget:(id *)target withObject:(id)object amount:(void *)amount callerToRetain:(id)caller;
622 #pragma mark talking to delegates
624 // Called when a request starts, lets the delegate know via didStartSelector
625 - (void)requestStarted;
627 // Called when a request receives response headers, lets the delegate know via didReceiveResponseHeadersSelector
628 - (void)requestReceivedResponseHeaders:(NSDictionary *)newHeaders;
630 // Called when a request completes successfully, lets the delegate know via didFinishSelector
631 - (void)requestFinished;
633 // Called when a request fails, and lets the delegate know via didFailSelector
634 - (void)failWithError:(NSError *)theError;
636 // Called to retry our request when our persistent connection is closed
637 // Returns YES if we haven't already retried, and connection will be restarted
638 // Otherwise, returns NO, and nothing will happen
639 - (BOOL)retryUsingNewConnection;
641 // Can be called by delegates from inside their willRedirectSelector implementations to restart the request with a new url
642 - (void)redirectToURL:(NSURL *)newURL;
644 #pragma mark parsing HTTP response headers
646 // Reads the response headers to find the content length, encoding, cookies for the session
647 // Also initiates request redirection when shouldRedirect is true
648 // And works out if HTTP auth is required
649 - (void)readResponseHeaders;
651 // Attempts to set the correct encoding by looking at the Content-Type header, if this is one
652 - (void)parseStringEncodingFromHeaders;
654 + (void)parseMimeType:(NSString **)mimeType andResponseEncoding:(NSStringEncoding *)stringEncoding fromContentType:(NSString *)contentType;
656 #pragma mark http authentication stuff
658 // Apply credentials to this request
659 - (BOOL)applyCredentials:(NSDictionary *)newCredentials;
660 - (BOOL)applyProxyCredentials:(NSDictionary *)newCredentials;
662 // Attempt to obtain credentials for this request from the URL, username and password or keychain
663 - (NSMutableDictionary *)findCredentials;
664 - (NSMutableDictionary *)findProxyCredentials;
666 // Unlock (unpause) the request thread so it can resume the request
667 // Should be called by delegates when they have populated the authentication information after an authentication challenge
668 - (void)retryUsingSuppliedCredentials;
670 // Should be called by delegates when they wish to cancel authentication and stop
671 - (void)cancelAuthentication;
673 // Apply authentication information and resume the request after an authentication challenge
674 - (void)attemptToApplyCredentialsAndResume;
675 - (void)attemptToApplyProxyCredentialsAndResume;
677 // 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
678 // Currently only used on iPhone OS
679 - (BOOL)showProxyAuthenticationDialog;
680 - (BOOL)showAuthenticationDialog;
682 // Construct a basic authentication header from the username and password supplied, and add it to the request headers
683 // Used when shouldPresentCredentialsBeforeChallenge is YES
684 - (void)addBasicAuthenticationHeaderWithUsername:(NSString *)theUsername andPassword:(NSString *)thePassword;
686 #pragma mark stream status handlers
688 // CFnetwork event handlers
689 - (void)handleNetworkEvent:(CFStreamEventType)type;
690 - (void)handleBytesAvailable;
691 - (void)handleStreamComplete;
692 - (void)handleStreamError;
696 // Cleans up and lets the queue know this operation is finished.
697 // Appears in this header for subclassing only, do not call this method from outside your request!
698 - (void)markAsFinished;
700 // Cleans up temporary files. There's normally no reason to call these yourself, they are called automatically when a request completes or fails
702 // Clean up the temporary file used to store the downloaded data when it comes in (if downloadDestinationPath is set)
703 - (BOOL)removeTemporaryDownloadFile;
705 // Clean up the temporary file used to store data that is inflated (decompressed) as it comes in
706 - (BOOL)removeTemporaryUncompressedDownloadFile;
708 // Clean up the temporary file used to store the request body (when shouldStreamPostDataFromDisk is YES)
709 - (BOOL)removeTemporaryUploadFile;
711 // Clean up the temporary file used to store a deflated (compressed) request body when shouldStreamPostDataFromDisk is YES
712 - (BOOL)removeTemporaryCompressedUploadFile;
714 // Remove a file on disk, returning NO and populating the passed error pointer if it fails
715 + (BOOL)removeFileAtPath:(NSString *)path error:(NSError **)err;
717 #pragma mark persistent connections
719 // Get the ID of the connection this request used (only really useful in tests and debugging)
720 - (NSNumber *)connectionID;
722 // Called automatically when a request is started to clean up any persistent connections that have expired
723 + (void)expirePersistentConnections;
725 #pragma mark default time out
727 + (NSTimeInterval)defaultTimeOutSeconds;
728 + (void)setDefaultTimeOutSeconds:(NSTimeInterval)newTimeOutSeconds;
730 #pragma mark client certificate
732 - (void)setClientCertificateIdentity:(SecIdentityRef)anIdentity;
734 #pragma mark session credentials
736 + (NSMutableArray *)sessionProxyCredentialsStore;
737 + (NSMutableArray *)sessionCredentialsStore;
739 + (void)storeProxyAuthenticationCredentialsInSessionStore:(NSDictionary *)credentials;
740 + (void)storeAuthenticationCredentialsInSessionStore:(NSDictionary *)credentials;
742 + (void)removeProxyAuthenticationCredentialsFromSessionStore:(NSDictionary *)credentials;
743 + (void)removeAuthenticationCredentialsFromSessionStore:(NSDictionary *)credentials;
745 - (NSDictionary *)findSessionProxyAuthenticationCredentials;
746 - (NSDictionary *)findSessionAuthenticationCredentials;
748 #pragma mark keychain storage
750 // Save credentials for this request to the keychain
751 - (void)saveCredentialsToKeychain:(NSDictionary *)newCredentials;
753 // Save credentials to the keychain
754 + (void)saveCredentials:(NSURLCredential *)credentials forHost:(NSString *)host port:(int)port protocol:(NSString *)protocol realm:(NSString *)realm;
755 + (void)saveCredentials:(NSURLCredential *)credentials forProxy:(NSString *)host port:(int)port realm:(NSString *)realm;
757 // Return credentials from the keychain
758 + (NSURLCredential *)savedCredentialsForHost:(NSString *)host port:(int)port protocol:(NSString *)protocol realm:(NSString *)realm;
759 + (NSURLCredential *)savedCredentialsForProxy:(NSString *)host port:(int)port protocol:(NSString *)protocol realm:(NSString *)realm;
761 // Remove credentials from the keychain
762 + (void)removeCredentialsForHost:(NSString *)host port:(int)port protocol:(NSString *)protocol realm:(NSString *)realm;
763 + (void)removeCredentialsForProxy:(NSString *)host port:(int)port realm:(NSString *)realm;
765 // We keep track of any cookies we accept, so that we can remove them from the persistent store later
766 + (void)setSessionCookies:(NSMutableArray *)newSessionCookies;
767 + (NSMutableArray *)sessionCookies;
769 // Adds a cookie to our list of cookies we've accepted, checking first for an old version of the same cookie and removing that
770 + (void)addSessionCookie:(NSHTTPCookie *)newCookie;
772 // Dump all session data (authentication and cookies)
773 + (void)clearSession;
775 #pragma mark get user agent
777 // Will be used as a user agent if requests do not specify a custom user agent
778 // Is only used when you have specified a Bundle Display Name (CFDisplayBundleName) or Bundle Name (CFBundleName) in your plist
779 + (NSString *)defaultUserAgentString;
781 #pragma mark proxy autoconfiguration
783 // Returns an array of proxies to use for a particular url, given the url of a PAC script
784 + (NSArray *)proxiesForURL:(NSURL *)theURL fromPAC:(NSURL *)pacScriptURL;
786 #pragma mark mime-type detection
788 // Return the mime type for a file
789 + (NSString *)mimeTypeForFileAtPath:(NSString *)path;
791 #pragma mark bandwidth measurement / throttling
793 // The maximum number of bytes ALL requests can send / receive in a second
794 // This is a rough figure. The actual amount used will be slightly more, this does not include HTTP headers
795 + (unsigned long)maxBandwidthPerSecond;
796 + (void)setMaxBandwidthPerSecond:(unsigned long)bytes;
798 // Get a rough average (for the last 5 seconds) of how much bandwidth is being used, in bytes
799 + (unsigned long)averageBandwidthUsedPerSecond;
801 - (void)performThrottling;
803 // Will return YES is bandwidth throttling is currently in use
804 + (BOOL)isBandwidthThrottled;
806 // Used internally to record bandwidth use, and by ASIInputStreams when uploading. It's probably best if you don't mess with this.
807 + (void)incrementBandwidthUsedInLastSecond:(unsigned long)bytes;
809 // On iPhone, ASIHTTPRequest can automatically turn throttling on and off as the connection type changes between WWAN and WiFi
812 // Set to YES to automatically turn on throttling when WWAN is connected, and automatically turn it off when it isn't
813 + (void)setShouldThrottleBandwidthForWWAN:(BOOL)throttle;
815 // Turns on throttling automatically when WWAN is connected using a custom limit, and turns it off automatically when it isn't
816 + (void)throttleBandwidthForWWANUsingLimit:(unsigned long)limit;
818 #pragma mark reachability
820 // Returns YES when an iPhone OS device is connected via WWAN, false when connected via WIFI or not connected
821 + (BOOL)isNetworkReachableViaWWAN;
827 // Returns the shared queue
828 + (NSOperationQueue *)sharedQueue;
832 + (void)setDefaultCache:(id <ASICacheDelegate>)cache;
833 + (id <ASICacheDelegate>)defaultCache;
835 // 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
836 + (unsigned long)maxUploadReadLength;
838 #pragma mark network activity
840 + (BOOL)isNetworkInUse;
842 + (void)setShouldUpdateNetworkActivityIndicator:(BOOL)shouldUpdate;
844 // Shows the network activity spinner thing on iOS. You may wish to override this to do something else in Mac projects
845 + (void)showNetworkActivityIndicator;
847 // Hides the network activity spinner thing on iOS
848 + (void)hideNetworkActivityIndicator;
850 #pragma mark miscellany
852 // Used for generating Authorization header when using basic authentication when shouldPresentCredentialsBeforeChallenge is true
853 // And also by ASIS3Request
854 + (NSString *)base64forData:(NSData *)theData;
856 // Returns a date from a string in RFC1123 format
857 + (NSDate *)dateFromRFC1123String:(NSString *)string;
860 // Used for detecting multitasking support at runtime (for backgrounding requests)
862 + (BOOL)isMultitaskingSupported;
865 #pragma mark threading behaviour
867 // In the default implementation, all requests run in a single background thread
868 // Advanced users only: Override this method in a subclass for a different threading behaviour
869 // Eg: return [NSThread mainThread] to run all requests in the main thread
870 // Alternatively, you can create a thread on demand, or manage a pool of threads
871 // Threads returned by this method will need to run the runloop in default mode (eg CFRunLoopRun())
872 // Requests will stop the runloop when they complete
873 // If you have multiple requests sharing the thread you'll need to restart the runloop when this happens
874 + (NSThread *)threadForRequest:(ASIHTTPRequest *)request;
879 @property (retain) NSString *username;
880 @property (retain) NSString *password;
881 @property (retain) NSString *domain;
883 @property (retain) NSString *proxyUsername;
884 @property (retain) NSString *proxyPassword;
885 @property (retain) NSString *proxyDomain;
887 @property (retain) NSString *proxyHost;
888 @property (assign) int proxyPort;
889 @property (retain) NSString *proxyType;
891 @property (retain,setter=setURL:, nonatomic) NSURL *url;
892 @property (retain) NSURL *originalURL;
893 @property (assign, nonatomic) id delegate;
894 @property (retain, nonatomic) id queue;
895 @property (assign, nonatomic) id uploadProgressDelegate;
896 @property (assign, nonatomic) id downloadProgressDelegate;
897 @property (assign) BOOL useKeychainPersistence;
898 @property (assign) BOOL useSessionPersistence;
899 @property (retain) NSString *downloadDestinationPath;
900 @property (retain) NSString *temporaryFileDownloadPath;
901 @property (retain) NSString *temporaryUncompressedDataDownloadPath;
902 @property (assign) SEL didStartSelector;
903 @property (assign) SEL didReceiveResponseHeadersSelector;
904 @property (assign) SEL willRedirectSelector;
905 @property (assign) SEL didFinishSelector;
906 @property (assign) SEL didFailSelector;
907 @property (assign) SEL didReceiveDataSelector;
908 @property (retain,readonly) NSString *authenticationRealm;
909 @property (retain,readonly) NSString *proxyAuthenticationRealm;
910 @property (retain) NSError *error;
911 @property (assign,readonly) BOOL complete;
912 @property (retain) NSDictionary *responseHeaders;
913 @property (retain) NSMutableDictionary *requestHeaders;
914 @property (retain) NSMutableArray *requestCookies;
915 @property (retain,readonly) NSArray *responseCookies;
916 @property (assign) BOOL useCookiePersistence;
917 @property (retain) NSDictionary *requestCredentials;
918 @property (retain) NSDictionary *proxyCredentials;
919 @property (assign,readonly) int responseStatusCode;
920 @property (retain,readonly) NSString *responseStatusMessage;
921 @property (retain) NSMutableData *rawResponseData;
922 @property (assign) NSTimeInterval timeOutSeconds;
923 @property (retain) NSString *requestMethod;
924 @property (retain) NSMutableData *postBody;
925 @property (assign) unsigned long long contentLength;
926 @property (assign) unsigned long long postLength;
927 @property (assign) BOOL shouldResetDownloadProgress;
928 @property (assign) BOOL shouldResetUploadProgress;
929 @property (assign) ASIHTTPRequest *mainRequest;
930 @property (assign) BOOL showAccurateProgress;
931 @property (assign) unsigned long long totalBytesRead;
932 @property (assign) unsigned long long totalBytesSent;
933 @property (assign) NSStringEncoding defaultResponseEncoding;
934 @property (assign) NSStringEncoding responseEncoding;
935 @property (assign) BOOL allowCompressedResponse;
936 @property (assign) BOOL allowResumeForFileDownloads;
937 @property (retain) NSDictionary *userInfo;
938 @property (retain) NSString *postBodyFilePath;
939 @property (assign) BOOL shouldStreamPostDataFromDisk;
940 @property (assign) BOOL didCreateTemporaryPostDataFile;
941 @property (assign) BOOL useHTTPVersionOne;
942 @property (assign, readonly) unsigned long long partialDownloadSize;
943 @property (assign) BOOL shouldRedirect;
944 @property (assign) BOOL validatesSecureCertificate;
945 @property (assign) BOOL shouldCompressRequestBody;
946 @property (retain) NSURL *PACurl;
947 @property (retain) NSString *authenticationScheme;
948 @property (retain) NSString *proxyAuthenticationScheme;
949 @property (assign) BOOL shouldPresentAuthenticationDialog;
950 @property (assign) BOOL shouldPresentProxyAuthenticationDialog;
951 @property (assign, readonly) ASIAuthenticationState authenticationNeeded;
952 @property (assign) BOOL shouldPresentCredentialsBeforeChallenge;
953 @property (assign, readonly) int authenticationRetryCount;
954 @property (assign, readonly) int proxyAuthenticationRetryCount;
955 @property (assign) BOOL haveBuiltRequestHeaders;
956 @property (assign, nonatomic) BOOL haveBuiltPostBody;
957 @property (assign, readonly) BOOL inProgress;
958 @property (assign) int numberOfTimesToRetryOnTimeout;
959 @property (assign, readonly) int retryCount;
960 @property (assign) BOOL shouldAttemptPersistentConnection;
961 @property (assign) NSTimeInterval persistentConnectionTimeoutSeconds;
962 @property (assign) BOOL shouldUseRFC2616RedirectBehaviour;
963 @property (assign, readonly) BOOL connectionCanBeReused;
964 @property (retain, readonly) NSNumber *requestID;
965 @property (assign) id <ASICacheDelegate> downloadCache;
966 @property (assign) ASICachePolicy cachePolicy;
967 @property (assign) ASICacheStoragePolicy cacheStoragePolicy;
968 @property (assign, readonly) BOOL didUseCachedResponse;
969 @property (assign) NSTimeInterval secondsToCache;
970 @property (retain) NSArray *clientCertificates;
971 #if TARGET_OS_IPHONE && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_4_0
972 @property (assign) BOOL shouldContinueWhenAppEntersBackground;
974 @property (retain) ASIDataDecompressor *dataDecompressor;
975 @property (assign) BOOL shouldWaitToInflateCompressedResponses;