![]() |
Ignite Tools
|
00001 // 00002 // UA_ASIHTTPRequest.h 00003 // 00004 // Created by Ben Copsey on 04/10/2007. 00005 // Copyright 2007-2010 All-Seeing Interactive. All rights reserved. 00006 // 00007 // A guide to the main features is available at: 00008 // http://allseeing-i.com/ASIHTTPRequest 00009 // 00010 // Portions are based on the ImageClient example from Apple: 00011 // See: http://developer.apple.com/samplecode/ImageClient/listing37.html 00012 00013 #import <Foundation/Foundation.h> 00014 #if TARGET_OS_IPHONE 00015 #import <CFNetwork/CFNetwork.h> 00016 #endif 00017 00018 #import <stdio.h> 00019 #import "UA_ASIHTTPRequestConfig.h" 00020 #import "UA_ASIHTTPRequestDelegate.h" 00021 #import "UA_ASIProgressDelegate.h" 00022 #import "UA_ASICacheDelegate.h" 00023 00024 @class UA_ASIDataDecompressor; 00025 00026 extern NSString *UA_ASIHTTPRequestVersion; 00027 00028 // Make targeting different platforms more reliable 00029 // See: http://www.blumtnwerx.com/blog/2009/06/cross-sdk-code-hygiene-in-xcode/ 00030 #ifndef __IPHONE_3_2 00031 #define __IPHONE_3_2 30200 00032 #endif 00033 #ifndef __IPHONE_4_0 00034 #define __IPHONE_4_0 40000 00035 #endif 00036 #ifndef __MAC_10_5 00037 #define __MAC_10_5 1050 00038 #endif 00039 #ifndef __MAC_10_6 00040 #define __MAC_10_6 1060 00041 #endif 00042 00043 typedef enum _UA_ASIAuthenticationState { 00044 UA_ASINoAuthenticationNeededYet = 0, 00045 UA_ASIHTTPAuthenticationNeeded = 1, 00046 UA_ASIProxyAuthenticationNeeded = 2 00047 } UA_ASIAuthenticationState; 00048 00049 typedef enum _UA_ASINetworkErrorType { 00050 UA_ASIConnectionFailureErrorType = 1, 00051 UA_ASIRequestTimedOutErrorType = 2, 00052 UA_ASIAuthenticationErrorType = 3, 00053 UA_ASIRequestCancelledErrorType = 4, 00054 UA_ASIUnableToCreateRequestErrorType = 5, 00055 UA_ASIInternalErrorWhileBuildingRequestType = 6, 00056 UA_ASIInternalErrorWhileApplyingCredentialsType = 7, 00057 UA_ASIFileManagementError = 8, 00058 UA_ASITooMuchRedirectionErrorType = 9, 00059 UA_ASIUnhandledExceptionError = 10, 00060 UA_ASICompressionError = 11 00061 00062 } UA_ASINetworkErrorType; 00063 00064 00065 // The error domain that all errors generated by UA_ASIHTTPRequest use 00066 extern NSString* const UA_NetworkRequestErrorDomain; 00067 00068 // You can use this number to throttle upload and download bandwidth in iPhone OS apps send or receive a large amount of data 00069 // This may help apps that might otherwise be rejected for inclusion into the app store for using excessive bandwidth 00070 // This number is not official, as far as I know there is no officially documented bandwidth limit 00071 extern unsigned long const UA_ASIWWANBandwidthThrottleAmount; 00072 00073 #if NS_BLOCKS_AVAILABLE 00074 typedef void (^UA_ASIBasicBlock)(void); 00075 typedef void (^UA_ASIHeadersBlock)(NSDictionary *responseHeaders); 00076 typedef void (^UA_ASISizeBlock)(long long size); 00077 typedef void (^UA_ASIProgressBlock)(unsigned long long size, unsigned long long total); 00078 typedef void (^UA_ASIDataBlock)(NSData *data); 00079 #endif 00080 00081 @interface UA_ASIHTTPRequest : NSOperation <NSCopying> { 00082 00083 // The url for this operation, should include GET params in the query string where appropriate 00084 NSURL *url; 00085 00086 // Will always contain the original url used for making the request (the value of url can change when a request is redirected) 00087 NSURL *originalURL; 00088 00089 // Temporarily stores the url we are about to redirect to. Will be nil again when we do redirect 00090 NSURL *redirectURL; 00091 00092 // The delegate, you need to manage setting and talking to your delegate in your subclasses 00093 id <UA_ASIHTTPRequestDelegate> delegate; 00094 00095 // Another delegate that is also notified of request status changes and progress updates 00096 // Generally, you won't use this directly, but UA_ASINetworkQueue sets itself as the queue so it can proxy updates to its own delegates 00097 // NOTE: WILL BE RETAINED BY THE REQUEST 00098 id <UA_ASIHTTPRequestDelegate, UA_ASIProgressDelegate> queue; 00099 00100 // HTTP method to use (GET / POST / PUT / DELETE / HEAD). Defaults to GET 00101 NSString *requestMethod; 00102 00103 // Request body - only used when the whole body is stored in memory (shouldStreamPostDataFromDisk is false) 00104 NSMutableData *postBody; 00105 00106 // gzipped request body used when shouldCompressRequestBody is YES 00107 NSData *compressedPostBody; 00108 00109 // When true, post body will be streamed from a file on disk, rather than loaded into memory at once (useful for large uploads) 00110 // Automatically set to true in ASIFormDataRequests when using setFile:forKey: 00111 BOOL shouldStreamPostDataFromDisk; 00112 00113 // Path to file used to store post body (when shouldStreamPostDataFromDisk is true) 00114 // You can set this yourself - useful if you want to PUT a file from local disk 00115 NSString *postBodyFilePath; 00116 00117 // Path to a temporary file used to store a deflated post body (when shouldCompressPostBody is YES) 00118 NSString *compressedPostBodyFilePath; 00119 00120 // Set to true when UA_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) 00121 BOOL didCreateTemporaryPostDataFile; 00122 00123 // Used when writing to the post body when shouldStreamPostDataFromDisk is true (via appendPostData: or appendPostDataFromFile:) 00124 NSOutputStream *postBodyWriteStream; 00125 00126 // Used for reading from the post body when sending the request 00127 NSInputStream *postBodyReadStream; 00128 00129 // Dictionary for custom HTTP request headers 00130 NSMutableDictionary *requestHeaders; 00131 00132 // Set to YES when the request header dictionary has been populated, used to prevent this happening more than once 00133 BOOL haveBuiltRequestHeaders; 00134 00135 // Will be populated with HTTP response headers from the server 00136 NSDictionary *responseHeaders; 00137 00138 // Can be used to manually insert cookie headers to a request, but it's more likely that sessionCookies will do this for you 00139 NSMutableArray *requestCookies; 00140 00141 // Will be populated with cookies 00142 NSArray *responseCookies; 00143 00144 // If use useCookiePersistence is true, network requests will present valid cookies from previous requests 00145 BOOL useCookiePersistence; 00146 00147 // 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 00148 BOOL useKeychainPersistence; 00149 00150 // If useSessionPersistence is true, network requests will save credentials and reuse for the duration of the session (until clearSession is called) 00151 BOOL useSessionPersistence; 00152 00153 // If allowCompressedResponse is true, requests will inform the server they can accept compressed data, and will automatically decompress gzipped responses. Default is true. 00154 BOOL allowCompressedResponse; 00155 00156 // If shouldCompressRequestBody is true, the request body will be gzipped. Default is false. 00157 // You will probably need to enable this feature on your webserver to make this work. Tested with apache only. 00158 BOOL shouldCompressRequestBody; 00159 00160 // When downloadDestinationPath is set, the result of this request will be downloaded to the file at this location 00161 // If downloadDestinationPath is not set, download data will be stored in memory 00162 NSString *downloadDestinationPath; 00163 00164 // The location that files will be downloaded to. Once a download is complete, files will be decompressed (if necessary) and moved to downloadDestinationPath 00165 NSString *temporaryFileDownloadPath; 00166 00167 // 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 00168 NSString *temporaryUncompressedDataDownloadPath; 00169 00170 // Used for writing data to a file when downloadDestinationPath is set 00171 NSOutputStream *fileDownloadOutputStream; 00172 00173 NSOutputStream *inflatedFileDownloadOutputStream; 00174 00175 // When the request fails or completes successfully, complete will be true 00176 BOOL complete; 00177 00178 // external "finished" indicator, subject of KVO notifications; updates after 'complete' 00179 BOOL finished; 00180 00181 // True if our 'cancel' selector has been called 00182 BOOL cancelled; 00183 00184 // If an error occurs, error will contain an NSError 00185 // If error code is = UA_ASIConnectionFailureErrorType (1, Connection failure occurred) - inspect [[error userInfo] objectForKey:NSUnderlyingErrorKey] for more information 00186 NSError *error; 00187 00188 // Username and password used for authentication 00189 NSString *username; 00190 NSString *password; 00191 00192 // Domain used for NTLM authentication 00193 NSString *domain; 00194 00195 // Username and password used for proxy authentication 00196 NSString *proxyUsername; 00197 NSString *proxyPassword; 00198 00199 // Domain used for NTLM proxy authentication 00200 NSString *proxyDomain; 00201 00202 // Delegate for displaying upload progress (usually an NSProgressIndicator, but you can supply a different object and handle this yourself) 00203 id <UA_ASIProgressDelegate> uploadProgressDelegate; 00204 00205 // Delegate for displaying download progress (usually an NSProgressIndicator, but you can supply a different object and handle this yourself) 00206 id <UA_ASIProgressDelegate> downloadProgressDelegate; 00207 00208 // Whether we've seen the headers of the response yet 00209 BOOL haveExaminedHeaders; 00210 00211 // Data we receive will be stored here. Data may be compressed unless allowCompressedResponse is false - you should use [request responseData] instead in most cases 00212 NSMutableData *rawResponseData; 00213 00214 // Used for sending and receiving data 00215 CFHTTPMessageRef request; 00216 NSInputStream *readStream; 00217 00218 // Used for authentication 00219 CFHTTPAuthenticationRef requestAuthentication; 00220 NSDictionary *requestCredentials; 00221 00222 // Used during NTLM authentication 00223 int authenticationRetryCount; 00224 00225 // Authentication scheme (Basic, Digest, NTLM) 00226 NSString *authenticationScheme; 00227 00228 // Realm for authentication when credentials are required 00229 NSString *authenticationRealm; 00230 00231 // When YES, UA_ASIHTTPRequest will present a dialog allowing users to enter credentials when no-matching credentials were found for a server that requires authentication 00232 // The dialog will not be shown if your delegate responds to authenticationNeededForRequest: 00233 // Default is NO. 00234 BOOL shouldPresentAuthenticationDialog; 00235 00236 // When YES, UA_ASIHTTPRequest will present a dialog allowing users to enter credentials when no-matching credentials were found for a proxy server that requires authentication 00237 // The dialog will not be shown if your delegate responds to proxyAuthenticationNeededForRequest: 00238 // Default is YES (basically, because most people won't want the hassle of adding support for authenticating proxies to their apps) 00239 BOOL shouldPresentProxyAuthenticationDialog; 00240 00241 // Used for proxy authentication 00242 CFHTTPAuthenticationRef proxyAuthentication; 00243 NSDictionary *proxyCredentials; 00244 00245 // Used during authentication with an NTLM proxy 00246 int proxyAuthenticationRetryCount; 00247 00248 // Authentication scheme for the proxy (Basic, Digest, NTLM) 00249 NSString *proxyAuthenticationScheme; 00250 00251 // Realm for proxy authentication when credentials are required 00252 NSString *proxyAuthenticationRealm; 00253 00254 // HTTP status code, eg: 200 = OK, 404 = Not found etc 00255 int responseStatusCode; 00256 00257 // Description of the HTTP status code 00258 NSString *responseStatusMessage; 00259 00260 // Size of the response 00261 unsigned long long contentLength; 00262 00263 // Size of the partially downloaded content 00264 unsigned long long partialDownloadSize; 00265 00266 // Size of the POST payload 00267 unsigned long long postLength; 00268 00269 // The total amount of downloaded data 00270 unsigned long long totalBytesRead; 00271 00272 // The total amount of uploaded data 00273 unsigned long long totalBytesSent; 00274 00275 // Last amount of data read (used for incrementing progress) 00276 unsigned long long lastBytesRead; 00277 00278 // Last amount of data sent (used for incrementing progress) 00279 unsigned long long lastBytesSent; 00280 00281 // This lock prevents the operation from being cancelled at an inopportune moment 00282 NSRecursiveLock *cancelledLock; 00283 00284 // Called on the delegate (if implemented) when the request starts. Default is requestStarted: 00285 SEL didStartSelector; 00286 00287 // Called on the delegate (if implemented) when the request receives response headers. Default is requestDidReceiveResponseHeaders: 00288 SEL didReceiveResponseHeadersSelector; 00289 00290 // Called on the delegate (if implemented) when the request receives a Location header and shouldRedirect is YES 00291 // The delegate can then change the url if needed, and can restart the request by calling [request resume], or simply cancel it 00292 SEL willRedirectSelector; 00293 00294 // Called on the delegate (if implemented) when the request completes successfully. Default is requestFinished: 00295 SEL didFinishSelector; 00296 00297 // Called on the delegate (if implemented) when the request fails. Default is requestFailed: 00298 SEL didFailSelector; 00299 00300 // Called on the delegate (if implemented) when the request receives data. Default is request:didReceiveData: 00301 // If you set this and implement the method in your delegate, you must handle the data yourself - UA_ASIHTTPRequest will not populate responseData or write the data to downloadDestinationPath 00302 SEL didReceiveDataSelector; 00303 00304 // 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 00305 NSDate *lastActivityTime; 00306 00307 // Number of seconds to wait before timing out - default is 10 00308 NSTimeInterval timeOutSeconds; 00309 00310 // Will be YES when a HEAD request will handle the content-length before this request starts 00311 BOOL shouldResetUploadProgress; 00312 BOOL shouldResetDownloadProgress; 00313 00314 // Used by HEAD requests when showAccurateProgress is YES to preset the content-length for this request 00315 UA_ASIHTTPRequest *mainRequest; 00316 00317 // When NO, this request will only update the progress indicator when it completes 00318 // When YES, this request will update the progress indicator according to how much data it has received so far 00319 // The default for requests is YES 00320 // Also see the comments in UA_ASINetworkQueue.h 00321 BOOL showAccurateProgress; 00322 00323 // Used to ensure the progress indicator is only incremented once when showAccurateProgress = NO 00324 BOOL updatedProgress; 00325 00326 // Prevents the body of the post being built more than once (largely for subclasses) 00327 BOOL haveBuiltPostBody; 00328 00329 // Used internally, may reflect the size of the internal buffer used by CFNetwork 00330 // POST / PUT operations with body sizes greater than uploadBufferSize will not timeout unless more than uploadBufferSize bytes have been sent 00331 // Likely to be 32KB on iPhone 3.0, 128KB on Mac OS X Leopard and iPhone 2.2.x 00332 unsigned long long uploadBufferSize; 00333 00334 // Text encoding for responses that do not send a Content-Type with a charset value. Defaults to NSISOLatin1StringEncoding 00335 NSStringEncoding defaultResponseEncoding; 00336 00337 // The text encoding of the response, will be defaultResponseEncoding if the server didn't specify. Can't be set. 00338 NSStringEncoding responseEncoding; 00339 00340 // Tells UA_ASIHTTPRequest not to delete partial downloads, and allows it to use an existing file to resume a download. Defaults to NO. 00341 BOOL allowResumeForFileDownloads; 00342 00343 // Custom user information associated with the request 00344 NSDictionary *userInfo; 00345 00346 // Use HTTP 1.0 rather than 1.1 (defaults to false) 00347 BOOL useHTTPVersionOne; 00348 00349 // When YES, requests will automatically redirect when they get a HTTP 30x header (defaults to YES) 00350 BOOL shouldRedirect; 00351 00352 // Used internally to tell the main loop we need to stop and retry with a new url 00353 BOOL needsRedirect; 00354 00355 // Incremented every time this request redirects. When it reaches 5, we give up 00356 int redirectCount; 00357 00358 // 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 00359 BOOL validatesSecureCertificate; 00360 00361 // If not nil and the URL scheme is https, CFNetwork configured to supply a client certificate 00362 SecIdentityRef clientCertificateIdentity; 00363 NSArray *clientCertificates; 00364 00365 // Details on the proxy to use - you could set these yourself, but it's probably best to let UA_ASIHTTPRequest detect the system proxy settings 00366 NSString *proxyHost; 00367 int proxyPort; 00368 00369 // UA_ASIHTTPRequest will assume kCFProxyTypeHTTP if the proxy type could not be automatically determined 00370 // Set to kCFProxyTypeSOCKS if you are manually configuring a SOCKS proxy 00371 NSString *proxyType; 00372 00373 // 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 00374 NSURL *PACurl; 00375 00376 // See UA_ASIAuthenticationState values above. 0 == default == No authentication needed yet 00377 UA_ASIAuthenticationState authenticationNeeded; 00378 00379 // When YES, ASIHTTPRequests will present credentials from the session store for requests to the same server before being asked for them 00380 // 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 00381 // Set to NO to only present credentials when explicitly asked for them 00382 // 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 00383 // Default is YES 00384 BOOL shouldPresentCredentialsBeforeChallenge; 00385 00386 // 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 00387 BOOL inProgress; 00388 00389 // Used internally to track whether the stream is scheduled on the run loop or not 00390 // Bandwidth throttling can unschedule the stream to slow things down while a request is in progress 00391 BOOL readStreamIsScheduled; 00392 00393 // Set to allow a request to automatically retry itself on timeout 00394 // Default is zero - timeout will stop the request 00395 int numberOfTimesToRetryOnTimeout; 00396 00397 // The number of times this request has retried (when numberOfTimesToRetryOnTimeout > 0) 00398 int retryCount; 00399 00400 // 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 00401 // Persistent connections will not be used if the server explicitly closes the connection 00402 // Default is YES 00403 BOOL shouldAttemptPersistentConnection; 00404 00405 // Number of seconds to keep an inactive persistent connection open on the client side 00406 // Default is 60 00407 // 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 00408 // A future date is created from this and used for expiring the connection, this is stored in connectionInfo's expires value 00409 NSTimeInterval persistentConnectionTimeoutSeconds; 00410 00411 // Set to yes when an appropriate keep-alive header is found 00412 BOOL connectionCanBeReused; 00413 00414 // Stores information about the persistent connection that is currently in use. 00415 // It may contain: 00416 // * The id we set for a particular connection, incremented every time we want to specify that we need a new connection 00417 // * The date that connection should expire 00418 // * 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) 00419 // * 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) 00420 // * 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. 00421 // 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 00422 NSMutableDictionary *connectionInfo; 00423 00424 // When set to YES, 301 and 302 automatic redirects will use the original method and and body, according to the HTTP 1.1 standard 00425 // Default is NO (to follow the behaviour of most browsers) 00426 BOOL shouldUseRFC2616RedirectBehaviour; 00427 00428 // Used internally to record when a request has finished downloading data 00429 BOOL downloadComplete; 00430 00431 // An ID that uniquely identifies this request - primarily used for debugging persistent connections 00432 NSNumber *requestID; 00433 00434 // Will be ASIHTTPRequestRunLoopMode for synchronous requests, NSDefaultRunLoopMode for all other requests 00435 NSString *runLoopMode; 00436 00437 // This timer checks up on the request every 0.25 seconds, and updates progress 00438 NSTimer *statusTimer; 00439 00440 00441 // The download cache that will be used for this request (use [UA_ASIHTTPRequest setDefaultCache:cache] to configure a default cache 00442 id <UA_ASICacheDelegate> downloadCache; 00443 00444 // The cache policy that will be used for this request - See UA_ASICacheDelegate.h for possible values 00445 UA_ASICachePolicy cachePolicy; 00446 00447 // The cache storage policy that will be used for this request - See UA_ASICacheDelegate.h for possible values 00448 UA_ASICacheStoragePolicy cacheStoragePolicy; 00449 00450 // Will be true when the response was pulled from the cache rather than downloaded 00451 BOOL didUseCachedResponse; 00452 00453 // Set secondsToCache to use a custom time interval for expiring the response when it is stored in a cache 00454 NSTimeInterval secondsToCache; 00455 00456 #if TARGET_OS_IPHONE && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_4_0 00457 BOOL shouldContinueWhenAppEntersBackground; 00458 UIBackgroundTaskIdentifier backgroundTask; 00459 #endif 00460 00461 00462 // When downloading a gzipped response, the request will use this helper object to inflate the response 00463 UA_ASIDataDecompressor *dataDecompressor; 00464 00465 // Controls how responses with a gzipped encoding are inflated (decompressed) 00466 // When set to YES (This is the default): 00467 // * gzipped responses for requests without a downloadDestinationPath will be inflated only when [request responseData] / [request responseString] is called 00468 // * gzipped responses for requests with a downloadDestinationPath set will be inflated only when the request completes 00469 // 00470 // When set to NO 00471 // All requests will inflate the response as it comes in 00472 // * If the request has no downloadDestinationPath set, the raw (compressed) response is discarded and rawResponseData will contain the decompressed response 00473 // * If the request has a downloadDestinationPath, the raw response will be stored in temporaryFileDownloadPath as normal, the inflated response will be stored in temporaryUncompressedDataDownloadPath 00474 // Once the request completes successfully, the contents of temporaryUncompressedDataDownloadPath are moved into downloadDestinationPath 00475 // 00476 // Setting this to NO may be especially useful for users using UA_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 00477 BOOL shouldWaitToInflateCompressedResponses; 00478 00479 #if NS_BLOCKS_AVAILABLE 00480 //block to execute when request starts 00481 UA_ASIBasicBlock startedBlock; 00482 00483 //block to execute when headers are received 00484 UA_ASIHeadersBlock headersReceivedBlock; 00485 00486 //block to execute when request completes successfully 00487 UA_ASIBasicBlock completionBlock; 00488 00489 //block to execute when request fails 00490 UA_ASIBasicBlock failureBlock; 00491 00492 //block for when bytes are received 00493 UA_ASIProgressBlock bytesReceivedBlock; 00494 00495 //block for when bytes are sent 00496 UA_ASIProgressBlock bytesSentBlock; 00497 00498 //block for when download size is incremented 00499 UA_ASISizeBlock downloadSizeIncrementedBlock; 00500 00501 //block for when upload size is incremented 00502 UA_ASISizeBlock uploadSizeIncrementedBlock; 00503 00504 //block for handling raw bytes received 00505 UA_ASIDataBlock dataReceivedBlock; 00506 00507 //block for handling authentication 00508 UA_ASIBasicBlock authenticationNeededBlock; 00509 00510 //block for handling proxy authentication 00511 UA_ASIBasicBlock proxyAuthenticationNeededBlock; 00512 00513 //block for handling redirections, if you want to 00514 UA_ASIBasicBlock requestRedirectedBlock; 00515 #endif 00516 } 00517 00518 #pragma mark init / dealloc 00519 00520 // Should be an HTTP or HTTPS url, may include username and password if appropriate 00521 - (id)initWithURL:(NSURL *)newURL; 00522 00523 // Convenience constructor 00524 + (id)requestWithURL:(NSURL *)newURL; 00525 00526 + (id)requestWithURL:(NSURL *)newURL usingCache:(id <UA_ASICacheDelegate>)cache; 00527 + (id)requestWithURL:(NSURL *)newURL usingCache:(id <UA_ASICacheDelegate>)cache andCachePolicy:(UA_ASICachePolicy)policy; 00528 00529 #if NS_BLOCKS_AVAILABLE 00530 - (void)setStartedBlock:(UA_ASIBasicBlock)aStartedBlock; 00531 - (void)setHeadersReceivedBlock:(UA_ASIHeadersBlock)aReceivedBlock; 00532 - (void)setCompletionBlock:(UA_ASIBasicBlock)aCompletionBlock; 00533 - (void)setFailedBlock:(UA_ASIBasicBlock)aFailedBlock; 00534 - (void)setBytesReceivedBlock:(UA_ASIProgressBlock)aBytesReceivedBlock; 00535 - (void)setBytesSentBlock:(UA_ASIProgressBlock)aBytesSentBlock; 00536 - (void)setDownloadSizeIncrementedBlock:(UA_ASISizeBlock) aDownloadSizeIncrementedBlock; 00537 - (void)setUploadSizeIncrementedBlock:(UA_ASISizeBlock) anUploadSizeIncrementedBlock; 00538 - (void)setDataReceivedBlock:(UA_ASIDataBlock)aReceivedBlock; 00539 - (void)setAuthenticationNeededBlock:(UA_ASIBasicBlock)anAuthenticationBlock; 00540 - (void)setProxyAuthenticationNeededBlock:(UA_ASIBasicBlock)aProxyAuthenticationBlock; 00541 - (void)setRequestRedirectedBlock:(UA_ASIBasicBlock)aRedirectBlock; 00542 #endif 00543 00544 #pragma mark setup request 00545 00546 // Add a custom header to the request 00547 - (void)addRequestHeader:(NSString *)header value:(NSString *)value; 00548 00549 // Called during buildRequestHeaders and after a redirect to create a cookie header from request cookies and the global store 00550 - (void)applyCookieHeader; 00551 00552 // Populate the request headers dictionary. Called before a request is started, or by a HEAD request that needs to borrow them 00553 - (void)buildRequestHeaders; 00554 00555 // Used to apply authorization header to a request before it is sent (when shouldPresentCredentialsBeforeChallenge is YES) 00556 - (void)applyAuthorizationHeader; 00557 00558 00559 // Create the post body 00560 - (void)buildPostBody; 00561 00562 // Called to add data to the post body. Will append to postBody when shouldStreamPostDataFromDisk is false, or write to postBodyWriteStream when true 00563 - (void)appendPostData:(NSData *)data; 00564 - (void)appendPostDataFromFile:(NSString *)file; 00565 00566 #pragma mark get information about this request 00567 00568 // Returns the contents of the result as an NSString (not appropriate for binary data - used responseData instead) 00569 - (NSString *)responseString; 00570 00571 // Response data, automatically uncompressed where appropriate 00572 - (NSData *)responseData; 00573 00574 // Returns true if the response was gzip compressed 00575 - (BOOL)isResponseCompressed; 00576 00577 #pragma mark running a request 00578 00579 00580 // Run a request synchronously, and return control when the request completes or fails 00581 - (void)startSynchronous; 00582 00583 // Run request in the background 00584 - (void)startAsynchronous; 00585 00586 // Clears all delegates and blocks, then cancels the request 00587 - (void)clearDelegatesAndCancel; 00588 00589 #pragma mark HEAD request 00590 00591 // Used by UA_ASINetworkQueue to create a HEAD request appropriate for this request with the same headers (though you can use it yourself) 00592 - (UA_ASIHTTPRequest *)HEADRequest; 00593 00594 #pragma mark upload/download progress 00595 00596 // Called approximately every 0.25 seconds to update the progress delegates 00597 - (void)updateProgressIndicators; 00598 00599 // Updates upload progress (notifies the queue and/or uploadProgressDelegate of this request) 00600 - (void)updateUploadProgress; 00601 00602 // Updates download progress (notifies the queue and/or uploadProgressDelegate of this request) 00603 - (void)updateDownloadProgress; 00604 00605 // Called when authorisation is needed, as we only find out we don't have permission to something when the upload is complete 00606 - (void)removeUploadProgressSoFar; 00607 00608 // Called when we get a content-length header and shouldResetDownloadProgress is true 00609 - (void)incrementDownloadSizeBy:(long long)length; 00610 00611 // Called when a request starts and shouldResetUploadProgress is true 00612 // Also called (with a negative length) to remove the size of the underlying buffer used for uploading 00613 - (void)incrementUploadSizeBy:(long long)length; 00614 00615 // Helper method for interacting with progress indicators to abstract the details of different APIS (NSProgressIndicator and UIProgressView) 00616 + (void)updateProgressIndicator:(id *)indicator withProgress:(unsigned long long)progress ofTotal:(unsigned long long)total; 00617 00618 // Helper method used for performing invocations on the main thread (used for progress) 00619 + (void)performSelector:(SEL)selector onTarget:(id *)target withObject:(id)object amount:(void *)amount callerToRetain:(id)caller; 00620 00621 #pragma mark talking to delegates 00622 00623 // Called when a request starts, lets the delegate know via didStartSelector 00624 - (void)requestStarted; 00625 00626 // Called when a request receives response headers, lets the delegate know via didReceiveResponseHeadersSelector 00627 - (void)requestReceivedResponseHeaders:(NSDictionary *)newHeaders; 00628 00629 // Called when a request completes successfully, lets the delegate know via didFinishSelector 00630 - (void)requestFinished; 00631 00632 // Called when a request fails, and lets the delegate know via didFailSelector 00633 - (void)failWithError:(NSError *)theError; 00634 00635 // Called to retry our request when our persistent connection is closed 00636 // Returns YES if we haven't already retried, and connection will be restarted 00637 // Otherwise, returns NO, and nothing will happen 00638 - (BOOL)retryUsingNewConnection; 00639 00640 // Can be called by delegates from inside their willRedirectSelector implementations to restart the request with a new url 00641 - (void)redirectToURL:(NSURL *)newURL; 00642 00643 #pragma mark parsing HTTP response headers 00644 00645 // Reads the response headers to find the content length, encoding, cookies for the session 00646 // Also initiates request redirection when shouldRedirect is true 00647 // And works out if HTTP auth is required 00648 - (void)readResponseHeaders; 00649 00650 // Attempts to set the correct encoding by looking at the Content-Type header, if this is one 00651 - (void)parseStringEncodingFromHeaders; 00652 00653 + (void)parseMimeType:(NSString **)mimeType andResponseEncoding:(NSStringEncoding *)stringEncoding fromContentType:(NSString *)contentType; 00654 00655 #pragma mark http authentication stuff 00656 00657 // Apply credentials to this request 00658 - (BOOL)applyCredentials:(NSDictionary *)newCredentials; 00659 - (BOOL)applyProxyCredentials:(NSDictionary *)newCredentials; 00660 00661 // Attempt to obtain credentials for this request from the URL, username and password or keychain 00662 - (NSMutableDictionary *)findCredentials; 00663 - (NSMutableDictionary *)findProxyCredentials; 00664 00665 // Unlock (unpause) the request thread so it can resume the request 00666 // Should be called by delegates when they have populated the authentication information after an authentication challenge 00667 - (void)retryUsingSuppliedCredentials; 00668 00669 // Should be called by delegates when they wish to cancel authentication and stop 00670 - (void)cancelAuthentication; 00671 00672 // Apply authentication information and resume the request after an authentication challenge 00673 - (void)attemptToApplyCredentialsAndResume; 00674 - (void)attemptToApplyProxyCredentialsAndResume; 00675 00676 // 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 00677 // Currently only used on iPhone OS 00678 - (BOOL)showProxyAuthenticationDialog; 00679 - (BOOL)showAuthenticationDialog; 00680 00681 // Construct a basic authentication header from the username and password supplied, and add it to the request headers 00682 // Used when shouldPresentCredentialsBeforeChallenge is YES 00683 - (void)addBasicAuthenticationHeaderWithUsername:(NSString *)theUsername andPassword:(NSString *)thePassword; 00684 00685 #pragma mark stream status handlers 00686 00687 // CFnetwork event handlers 00688 - (void)handleNetworkEvent:(CFStreamEventType)type; 00689 - (void)handleBytesAvailable; 00690 - (void)handleStreamComplete; 00691 - (void)handleStreamError; 00692 00693 #pragma mark cleanup 00694 00695 // Cleans up and lets the queue know this operation is finished. 00696 // Appears in this header for subclassing only, do not call this method from outside your request! 00697 - (void)markAsFinished; 00698 00699 // Cleans up temporary files. There's normally no reason to call these yourself, they are called automatically when a request completes or fails 00700 00701 // Clean up the temporary file used to store the downloaded data when it comes in (if downloadDestinationPath is set) 00702 - (BOOL)removeTemporaryDownloadFile; 00703 00704 // Clean up the temporary file used to store data that is inflated (decompressed) as it comes in 00705 - (BOOL)removeTemporaryUncompressedDownloadFile; 00706 00707 // Clean up the temporary file used to store the request body (when shouldStreamPostDataFromDisk is YES) 00708 - (BOOL)removeTemporaryUploadFile; 00709 00710 // Clean up the temporary file used to store a deflated (compressed) request body when shouldStreamPostDataFromDisk is YES 00711 - (BOOL)removeTemporaryCompressedUploadFile; 00712 00713 // Remove a file on disk, returning NO and populating the passed error pointer if it fails 00714 + (BOOL)removeFileAtPath:(NSString *)path error:(NSError **)err; 00715 00716 #pragma mark persistent connections 00717 00718 // Get the ID of the connection this request used (only really useful in tests and debugging) 00719 - (NSNumber *)connectionID; 00720 00721 // Called automatically when a request is started to clean up any persistent connections that have expired 00722 + (void)expirePersistentConnections; 00723 00724 #pragma mark default time out 00725 00726 + (NSTimeInterval)defaultTimeOutSeconds; 00727 + (void)setDefaultTimeOutSeconds:(NSTimeInterval)newTimeOutSeconds; 00728 00729 #pragma mark client certificate 00730 00731 - (void)setClientCertificateIdentity:(SecIdentityRef)anIdentity; 00732 00733 #pragma mark session credentials 00734 00735 + (NSMutableArray *)sessionProxyCredentialsStore; 00736 + (NSMutableArray *)sessionCredentialsStore; 00737 00738 + (void)storeProxyAuthenticationCredentialsInSessionStore:(NSDictionary *)credentials; 00739 + (void)storeAuthenticationCredentialsInSessionStore:(NSDictionary *)credentials; 00740 00741 + (void)removeProxyAuthenticationCredentialsFromSessionStore:(NSDictionary *)credentials; 00742 + (void)removeAuthenticationCredentialsFromSessionStore:(NSDictionary *)credentials; 00743 00744 - (NSDictionary *)findSessionProxyAuthenticationCredentials; 00745 - (NSDictionary *)findSessionAuthenticationCredentials; 00746 00747 #pragma mark keychain storage 00748 00749 // Save credentials for this request to the keychain 00750 - (void)saveCredentialsToKeychain:(NSDictionary *)newCredentials; 00751 00752 // Save credentials to the keychain 00753 + (void)saveCredentials:(NSURLCredential *)credentials forHost:(NSString *)host port:(int)port protocol:(NSString *)protocol realm:(NSString *)realm; 00754 + (void)saveCredentials:(NSURLCredential *)credentials forProxy:(NSString *)host port:(int)port realm:(NSString *)realm; 00755 00756 // Return credentials from the keychain 00757 + (NSURLCredential *)savedCredentialsForHost:(NSString *)host port:(int)port protocol:(NSString *)protocol realm:(NSString *)realm; 00758 + (NSURLCredential *)savedCredentialsForProxy:(NSString *)host port:(int)port protocol:(NSString *)protocol realm:(NSString *)realm; 00759 00760 // Remove credentials from the keychain 00761 + (void)removeCredentialsForHost:(NSString *)host port:(int)port protocol:(NSString *)protocol realm:(NSString *)realm; 00762 + (void)removeCredentialsForProxy:(NSString *)host port:(int)port realm:(NSString *)realm; 00763 00764 // We keep track of any cookies we accept, so that we can remove them from the persistent store later 00765 + (void)setSessionCookies:(NSMutableArray *)newSessionCookies; 00766 + (NSMutableArray *)sessionCookies; 00767 00768 // Adds a cookie to our list of cookies we've accepted, checking first for an old version of the same cookie and removing that 00769 + (void)addSessionCookie:(NSHTTPCookie *)newCookie; 00770 00771 // Dump all session data (authentication and cookies) 00772 + (void)clearSession; 00773 00774 #pragma mark get user agent 00775 00776 // Will be used as a user agent if requests do not specify a custom user agent 00777 // Is only used when you have specified a Bundle Display Name (CFDisplayBundleName) or Bundle Name (CFBundleName) in your plist 00778 + (NSString *)defaultUserAgentString; 00779 00780 #pragma mark proxy autoconfiguration 00781 00782 // Returns an array of proxies to use for a particular url, given the url of a PAC script 00783 + (NSArray *)proxiesForURL:(NSURL *)theURL fromPAC:(NSURL *)pacScriptURL; 00784 00785 #pragma mark mime-type detection 00786 00787 // Return the mime type for a file 00788 + (NSString *)mimeTypeForFileAtPath:(NSString *)path; 00789 00790 #pragma mark bandwidth measurement / throttling 00791 00792 // The maximum number of bytes ALL requests can send / receive in a second 00793 // This is a rough figure. The actual amount used will be slightly more, this does not include HTTP headers 00794 + (unsigned long)maxBandwidthPerSecond; 00795 + (void)setMaxBandwidthPerSecond:(unsigned long)bytes; 00796 00797 // Get a rough average (for the last 5 seconds) of how much bandwidth is being used, in bytes 00798 + (unsigned long)averageBandwidthUsedPerSecond; 00799 00800 - (void)performThrottling; 00801 00802 // Will return YES is bandwidth throttling is currently in use 00803 + (BOOL)isBandwidthThrottled; 00804 00805 // Used internally to record bandwidth use, and by ASIInputStreams when uploading. It's probably best if you don't mess with this. 00806 + (void)incrementBandwidthUsedInLastSecond:(unsigned long)bytes; 00807 00808 // On iPhone, UA_ASIHTTPRequest can automatically turn throttling on and off as the connection type changes between WWAN and WiFi 00809 00810 #if TARGET_OS_IPHONE 00811 // Set to YES to automatically turn on throttling when WWAN is connected, and automatically turn it off when it isn't 00812 + (void)setShouldThrottleBandwidthForWWAN:(BOOL)throttle; 00813 00814 // Turns on throttling automatically when WWAN is connected using a custom limit, and turns it off automatically when it isn't 00815 + (void)throttleBandwidthForWWANUsingLimit:(unsigned long)limit; 00816 00817 #pragma mark reachability 00818 00819 // Returns YES when an iPhone OS device is connected via WWAN, false when connected via WIFI or not connected 00820 + (BOOL)isNetworkReachableViaWWAN; 00821 00822 #endif 00823 00824 #pragma mark queue 00825 00826 // Returns the shared queue 00827 + (NSOperationQueue *)sharedQueue; 00828 00829 #pragma mark cache 00830 00831 + (void)setDefaultCache:(id <UA_ASICacheDelegate>)cache; 00832 + (id <UA_ASICacheDelegate>)defaultCache; 00833 00834 // 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 00835 + (unsigned long)maxUploadReadLength; 00836 00837 #pragma mark network activity 00838 00839 + (BOOL)isNetworkInUse; 00840 00841 + (void)setShouldUpdateNetworkActivityIndicator:(BOOL)shouldUpdate; 00842 00843 // Shows the network activity spinner thing on iOS. You may wish to override this to do something else in Mac projects 00844 + (void)showNetworkActivityIndicator; 00845 00846 // Hides the network activity spinner thing on iOS 00847 + (void)hideNetworkActivityIndicator; 00848 00849 #pragma mark miscellany 00850 00851 // Used for generating Authorization header when using basic authentication when shouldPresentCredentialsBeforeChallenge is true 00852 // And also by ASIS3Request 00853 + (NSString *)base64forData:(NSData *)theData; 00854 00855 // Returns a date from a string in RFC1123 format 00856 + (NSDate *)dateFromRFC1123String:(NSString *)string; 00857 00858 00859 // Used for detecting multitasking support at runtime (for backgrounding requests) 00860 #if TARGET_OS_IPHONE 00861 + (BOOL)isMultitaskingSupported; 00862 #endif 00863 00864 #pragma mark threading behaviour 00865 00866 // In the default implementation, all requests run in a single background thread 00867 // Advanced users only: Override this method in a subclass for a different threading behaviour 00868 // Eg: return [NSThread mainThread] to run all requests in the main thread 00869 // Alternatively, you can create a thread on demand, or manage a pool of threads 00870 // Threads returned by this method will need to run the runloop in default mode (eg CFRunLoopRun()) 00871 // Requests will stop the runloop when they complete 00872 // If you have multiple requests sharing the thread you'll need to restart the runloop when this happens 00873 + (NSThread *)threadForRequest:(UA_ASIHTTPRequest *)request; 00874 00875 00876 #pragma mark === 00877 00878 @property (retain) NSString *username; 00879 @property (retain) NSString *password; 00880 @property (retain) NSString *domain; 00881 00882 @property (retain) NSString *proxyUsername; 00883 @property (retain) NSString *proxyPassword; 00884 @property (retain) NSString *proxyDomain; 00885 00886 @property (retain) NSString *proxyHost; 00887 @property (assign) int proxyPort; 00888 @property (retain) NSString *proxyType; 00889 00890 @property (retain,setter=setURL:, nonatomic) NSURL *url; 00891 @property (retain) NSURL *originalURL; 00892 @property (assign, nonatomic) id delegate; 00893 @property (retain, nonatomic) id queue; 00894 @property (assign, nonatomic) id uploadProgressDelegate; 00895 @property (assign, nonatomic) id downloadProgressDelegate; 00896 @property (assign) BOOL useKeychainPersistence; 00897 @property (assign) BOOL useSessionPersistence; 00898 @property (retain) NSString *downloadDestinationPath; 00899 @property (retain) NSString *temporaryFileDownloadPath; 00900 @property (retain) NSString *temporaryUncompressedDataDownloadPath; 00901 @property (assign) SEL didStartSelector; 00902 @property (assign) SEL didReceiveResponseHeadersSelector; 00903 @property (assign) SEL willRedirectSelector; 00904 @property (assign) SEL didFinishSelector; 00905 @property (assign) SEL didFailSelector; 00906 @property (assign) SEL didReceiveDataSelector; 00907 @property (retain,readonly) NSString *authenticationRealm; 00908 @property (retain,readonly) NSString *proxyAuthenticationRealm; 00909 @property (retain) NSError *error; 00910 @property (assign,readonly) BOOL complete; 00911 @property (retain) NSDictionary *responseHeaders; 00912 @property (retain) NSMutableDictionary *requestHeaders; 00913 @property (retain) NSMutableArray *requestCookies; 00914 @property (retain,readonly) NSArray *responseCookies; 00915 @property (assign) BOOL useCookiePersistence; 00916 @property (retain) NSDictionary *requestCredentials; 00917 @property (retain) NSDictionary *proxyCredentials; 00918 @property (assign,readonly) int responseStatusCode; 00919 @property (retain,readonly) NSString *responseStatusMessage; 00920 @property (retain) NSMutableData *rawResponseData; 00921 @property (assign) NSTimeInterval timeOutSeconds; 00922 @property (retain) NSString *requestMethod; 00923 @property (retain) NSMutableData *postBody; 00924 @property (assign) unsigned long long contentLength; 00925 @property (assign) unsigned long long postLength; 00926 @property (assign) BOOL shouldResetDownloadProgress; 00927 @property (assign) BOOL shouldResetUploadProgress; 00928 @property (assign) UA_ASIHTTPRequest *mainRequest; 00929 @property (assign) BOOL showAccurateProgress; 00930 @property (assign) unsigned long long totalBytesRead; 00931 @property (assign) unsigned long long totalBytesSent; 00932 @property (assign) NSStringEncoding defaultResponseEncoding; 00933 @property (assign) NSStringEncoding responseEncoding; 00934 @property (assign) BOOL allowCompressedResponse; 00935 @property (assign) BOOL allowResumeForFileDownloads; 00936 @property (retain) NSDictionary *userInfo; 00937 @property (retain) NSString *postBodyFilePath; 00938 @property (assign) BOOL shouldStreamPostDataFromDisk; 00939 @property (assign) BOOL didCreateTemporaryPostDataFile; 00940 @property (assign) BOOL useHTTPVersionOne; 00941 @property (assign, readonly) unsigned long long partialDownloadSize; 00942 @property (assign) BOOL shouldRedirect; 00943 @property (assign) BOOL validatesSecureCertificate; 00944 @property (assign) BOOL shouldCompressRequestBody; 00945 @property (retain) NSURL *PACurl; 00946 @property (retain) NSString *authenticationScheme; 00947 @property (retain) NSString *proxyAuthenticationScheme; 00948 @property (assign) BOOL shouldPresentAuthenticationDialog; 00949 @property (assign) BOOL shouldPresentProxyAuthenticationDialog; 00950 @property (assign, readonly) UA_ASIAuthenticationState authenticationNeeded; 00951 @property (assign) BOOL shouldPresentCredentialsBeforeChallenge; 00952 @property (assign, readonly) int authenticationRetryCount; 00953 @property (assign, readonly) int proxyAuthenticationRetryCount; 00954 @property (assign) BOOL haveBuiltRequestHeaders; 00955 @property (assign, nonatomic) BOOL haveBuiltPostBody; 00956 @property (assign, readonly) BOOL inProgress; 00957 @property (assign) int numberOfTimesToRetryOnTimeout; 00958 @property (assign, readonly) int retryCount; 00959 @property (assign) BOOL shouldAttemptPersistentConnection; 00960 @property (assign) NSTimeInterval persistentConnectionTimeoutSeconds; 00961 @property (assign) BOOL shouldUseRFC2616RedirectBehaviour; 00962 @property (assign, readonly) BOOL connectionCanBeReused; 00963 @property (retain, readonly) NSNumber *requestID; 00964 @property (assign) id <UA_ASICacheDelegate> downloadCache; 00965 @property (assign) UA_ASICachePolicy cachePolicy; 00966 @property (assign) UA_ASICacheStoragePolicy cacheStoragePolicy; 00967 @property (assign, readonly) BOOL didUseCachedResponse; 00968 @property (assign) NSTimeInterval secondsToCache; 00969 @property (retain) NSArray *clientCertificates; 00970 #if TARGET_OS_IPHONE && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_4_0 00971 @property (assign) BOOL shouldContinueWhenAppEntersBackground; 00972 #endif 00973 @property (retain) UA_ASIDataDecompressor *dataDecompressor; 00974 @property (assign) BOOL shouldWaitToInflateCompressedResponses; 00975 00976 @end