Repository navigation
Expand file tree
/
Copy pathFSNConnection.m
More file actions
829 lines (568 loc) · 22.9 KB
/
Copy pathFSNConnection.m
File metadata and controls
829 lines (568 loc) · 22.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
//
// FSNConnection.m
// FSN
//
// Created by George King on 7/14/11.
// Copyright 2011-2012 Foursquare Labs, Inc. All rights reserved.
// Permission to use this file is granted in FSNetworking/license.txt (apache v2).
//
#import "FSNData.h"
#import "FSNConnection.h"
// Typically, FSN_QUEUED_CONNECTIONS is set to 0 or 1 in the target's prefix header.
// Note that NSURLConnection setDelegateQueue appears to be broken on iOS 5.1, causing application-wide deadlocks.
// See README.md for details.
#if FSN_QUEUED_CONNECTIONS
#if TARGET_OS_IPHONE
#warning "NSURLConnection using setDelegateQueue is known to deadlock on iOS 5"
#endif
#endif
NSString * const FSNConnectionActivityBegan = @"FSNConnectionActivityBegan";
NSString * const FSNConnectionActivityEnded = @"FSNConnectionActivityEnded";
NSString* stringForRequestMethod(FSNRequestMethod method) {
switch (method) {
case FSNRequestMethodGET: return @"GET";
case FSNRequestMethodPOST: return @"POST";
default:
NSCAssert(0, @"unknown request method");
return nil;
}
}
@interface FSNConnection ()
// public readonly
@property (nonatomic, strong, readwrite) NSURLResponse *response;
@property (nonatomic, strong, readwrite) id<NSObject> parseResult;
@property (nonatomic, strong, readwrite) NSError *error;
@property (nonatomic, readwrite) BOOL didStart;
@property (nonatomic, readwrite) BOOL didFinishLoading;
@property (nonatomic, readwrite) BOOL didComplete;
@property (nonatomic, readwrite) long long uploadProgressBytes;
@property (nonatomic, readwrite) long long uploadExpectedBytes;
@property (nonatomic, readwrite) long long downloadProgressBytes;
@property (nonatomic, readwrite) NSUInteger concurrencyCountAtStart;
@property (nonatomic, readwrite) NSTimeInterval startTime;
@property (nonatomic, readwrite) NSTimeInterval challengeInterval;
@property (nonatomic, readwrite) NSTimeInterval responseInterval;
@property (nonatomic, readwrite) NSTimeInterval finishOrFailInterval;
@property (nonatomic, readwrite) NSTimeInterval parseInterval;
// private
@property (nonatomic, readwrite) NSMutableData *mutableResponseData;
@property (nonatomic) NSURLConnection *connection;
@property (nonatomic) NSRecursiveLock *blocksLock;
#if TARGET_OS_IPHONE
@property (nonatomic) UIBackgroundTaskIdentifier taskIdentifier;
#endif
@end
@implementation FSNConnection
#pragma mark - NSObject
- (void)dealloc {
NSAssert(!self.connection, @"non-nil connection: %@", self.connection);
#if TARGET_OS_IPHONE
// if this task was set to run in background then the expiration handler should be retaining self
NSAssert1(self.taskIdentifier == UIBackgroundTaskInvalid,
@"deallocated request has background task identifier: %@", self);
#endif
[self clearBlocks]; // not cleanup; assert no taskIdentifer above instead
// just to be safe in production
[self.connection cancel];
}
- (NSString*)description {
return
[NSString stringWithFormat:
@"<%@: %p | parse:%@ fin:%@ prog:%@ | "
@"cn:%@ res:%@ err:%@ | "
@"st:%@ fl:%@ comp:%@ succ:%@ | url: %@>",
self.class, self, BIT_YN(self.parseBlock), BIT_YN(self.completionBlock), BIT_YN(self.progressBlock),
BIT_YN(self.connection), BIT_YN(self.parseResult), BIT_YN(self.error),
BIT_YN(self.didStart), BIT_YN(self.didFinishLoading), BIT_YN(self.didComplete), BIT_YN(self.didSucceed),
self.url];
}
- (id)init {
INIT([super init]);
// protect executing blocks from being dealloced; lock is recursive because:
// - calling clearBlocks may cause an object in the block closure to be released
// - that may in turn 'own' the connection, and call clearBlocks to properly break retain cycles in all cases.
self.blocksLock = [NSRecursiveLock new];
return self;
}
#pragma mark - NSURLConnectionDelegate
// MARK: redirects
// called whenever an NSURLConnection determines that it must change URLs in order to continue loading a request.
// TODO: support redirect modification with a redirectBlock or delegate?
- (NSURLRequest *)connection:(NSURLConnection *)connection
willSendRequest:(NSURLRequest *)request
redirectResponse:(NSURLResponse *)response {
FSNVerbose(@"%p: willSendRequest", self);
return request;
}
// called whenever an NSURLConnection determines that the client needs to provide a new, unopened body stream.
// TODO: support streams with streamBlock or delegate?
//- (NSInputStream *)connection:(NSURLConnection *)connection needNewBodyStream:(NSURLRequest *)request {
// FSNVerbose(@"%p: needNewBodyStream", self);
//}
// MARK: authentication
// TODO: support authenticationBlock or delegate?
- (BOOL)connectionShouldUseCredentialStorage:(NSURLConnection *)connection {
FSNVerbose(@"%p: connectionShouldUseCredentialStorage", self);
return YES; // default (same as not implementing the delegate callback)
}
- (void)connection:(NSURLConnection *)connection
willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
FSNVerbose(@"%p: willSendRequestForAuthenticationChallenge", self);
self.challengeInterval = [self intervalSinceStart];
[challenge.sender performDefaultHandlingForAuthenticationChallenge:challenge];
}
// MARK: response
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
FSNVerbose(@"%p: didReceiveResponse", self);
FSNVerbose(@"Response Headers: %@", [response allHeaderFields]);
self.responseInterval = [self intervalSinceStart];
// according to apple docs, this method may be called more than once in rare cases (similar to body stream case)
// for this reason, responseData should be initialized/reset here
self.response = response;
if (self.responseStream) {
[self.responseStream open];
}
else {
self.mutableResponseData = [NSMutableData data];
}
}
- (void)connection:(NSURLConnection *)connection
didSendBodyData:(NSInteger)bytesWritten
totalBytesWritten:(NSInteger)totalBytesWritten
totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite {
FSNVerbose(@"%p: didSendBodyData", self);
self.uploadProgressBytes = totalBytesWritten;
self.uploadExpectedBytes = totalBytesExpectedToWrite;
[self performReportProgress];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
FSNVerbose(@"%p: didReceiveData", self);
if (self.responseStream) {
[self.responseStream write:data.bytes maxLength:data.length];
self.downloadProgressBytes += data.length;
}
else {
[self.mutableResponseData appendData:data];
self.downloadProgressBytes = self.mutableResponseData.length;
}
[self performReportProgress];
}
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
willCacheResponse:(NSCachedURLResponse *)cachedResponse {
FSNVerbose(@"%p: willCacheResponse;\n cachedResponse: %@", self, cachedResponse);
return cachedResponse; // return nil to circumvent caching
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
FSNVerbose(@"%p: didFinishLoading", self);
self.finishOrFailInterval = [self intervalSinceStart];
[self.responseStream close];
self.didFinishLoading = YES;
if (self.parseBlock) {
[self callOrDispatchParse];
}
else {
[self performComplete];
}
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
FSNVerbose(@"%p: didFail", self);
self.finishOrFailInterval = [self intervalSinceStart];
[self.responseStream close];
[self failWithError:error];
}
#pragma mark - FSNConnection
#if FSN_QUEUED_CONNECTIONS
+ (NSOperationQueue *)queue {
static NSOperationQueue *q = nil;
if (!q) {
q = [NSOperationQueue new];
q.name = @"FSNConnection queue";
}
return q;
}
#endif
+ (NSMutableSet *)mutableConnections {
static NSMutableSet *set = nil;
if (!set) {
set = [NSMutableSet new];
}
return set;
}
// publicly expose the connection set as read-only
+ (NSSet *)connections {
return [self mutableConnections];
}
+ (void)cancelAllConnections {
for (FSNConnection *c in [[self connections] allObjects]) {
[c cancel];
}
}
+ (id)withUrl:(NSURL *)url
method:(FSNRequestMethod)method
headers:(NSDictionary*)headers
parameters:(NSDictionary*)parameters
parseBlock:(FSNParseBlock)parseBlock
completionBlock:(FSNCompletionBlock)completionBlock
progressBlock:(FSNProgressBlock)progressBlock {
FSNConnection *c = [FSNConnection new];
c.url = url;
c.method = method;
c.headers = headers;
c.parameters = parameters;
c.parseBlock = parseBlock;
c.completionBlock = completionBlock;
c.progressBlock = progressBlock;
#if TARGET_OS_IPHONE
c.shouldRunInBackground = (method == FSNRequestMethodPOST);
c.taskIdentifier = UIBackgroundTaskInvalid;
#endif
return c;
}
// MARK: accessors
- (BOOL)didSucceed {
return self.didComplete && !self.error;
}
- (NSHTTPURLResponse *)httpResponse {
return KIND_OR_NIL(self.response, NSHTTPURLResponse);
}
- (NSData *)responseData {
return self.mutableResponseData;
}
- (NSTimeInterval)intervalSinceStart {
return [NSDate posixTime] - self.startTime;
}
#define ASSERT_UNSTARTED \
NSAssert(!self.didStart, @"method cannot be called after start: %s", __FUNCTION__)
- (void)setUrl:(NSURL *)url {
ASSERT_UNSTARTED;
_url = url;
}
- (void)setMethod:(FSNRequestMethod)method {
ASSERT_UNSTARTED;
_method = method;
}
#if TARGET_OS_IPHONE
- (void)setShouldRunInBackground:(BOOL)shouldRunInBackground {
ASSERT_UNSTARTED;
_shouldRunInBackground = shouldRunInBackground;
}
#endif
- (void)setHeaders:(NSDictionary *)headers {
ASSERT_UNSTARTED;
_headers = headers;
}
- (void)setParameters:(NSDictionary *)parameters {
ASSERT_UNSTARTED;
_parameters = parameters;
}
- (void)setResponseStream:(NSOutputStream *)responseStream {
ASSERT_UNSTARTED;
_responseStream = responseStream;
}
// MARK: life cycle
- (void)clearBlocks {
[self.blocksLock lock];
self.parseBlock = nil;
self.completionBlock = nil;
self.progressBlock = nil;
[self.blocksLock unlock];
}
- (void)cleanup {
[self clearBlocks];
#if TARGET_OS_IPHONE
[self endBackgroundTask];
#endif
NSMutableSet *requests = [self.class mutableConnections];
[requests removeObject:self];
if (requests.count == 0) {
[[NSNotificationCenter defaultCenter] postNotificationName:FSNConnectionActivityEnded object:nil];
}
}
- (void)cancelConnection {
FSNVerbose(@"%p: cancelConnection", self);
[self.connection cancel]; // releases delegate (self)
self.connection = nil;
}
- (void)callOrDispatchParse {
#if FSN_QUEUED_CONNECTIONS
[self parse];
#else
// dispatch to the medium priority global queue
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self parse];
});
#endif
}
// performed on a background thread, either via connection queue (mac) or dispatch_async (ios)
- (void)parse {
ASSERT_NOT_MAIN_THREAD;
NSError *error = nil;
// because the connection could get canceled after the block calling this method is dispatched,
// we must both lock out out concurrent cancellation, and check that the parse block still exists.
[self.blocksLock lock];
if (self.parseBlock) {
self.parseResult = self.parseBlock(self, &error);
self.parseInterval = [self intervalSinceStart];
if (error) {
[self failWithError:error];
}
else {
[self performComplete];
}
}
[self.blocksLock unlock];
}
- (void)failWithError:(NSError *)error {
FSNLog(@"failWithError: %@\n error: %@", self, error);
NSAssert(!self.error, @"error already set");
self.error = error;
[self performComplete];
}
- (void)performComplete {
FSNVerbose(@"%p: performComplete", self);
self.connection = nil;
[self performSelectorOnMainThread:@selector(complete) withObject:nil waitUntilDone:NO]; // call retains self
}
- (void)complete {
ASSERT_MAIN_THREAD;
self.didComplete = YES;
[self reportProgress];
[self.blocksLock lock];
if (self.completionBlock) {
self.completionBlock(self);
}
[self.blocksLock unlock];
[self cleanup];
}
// MARK: public
// returns self, or nil if start fails
- (FSNConnection *)start {
// TODO: replace this assertion with failWithError: (never add to queue)
NSAssert(self.url, @"nil url");
FSNVerbose(@"%p: enqueue (#%d)", self, [[self.class connections] count]);
self.startTime = [NSDate posixTime];
NSMutableSet *connections = [self.class mutableConnections];
[connections addObject:self];
self.concurrencyCountAtStart = [self.class mutableConnections].count;
if (connections.count == 1) {
[[NSNotificationCenter defaultCenter] postNotificationName:FSNConnectionActivityBegan object:nil];
}
self.didStart = YES;
#if TARGET_OS_IPHONE
if (self.shouldRunInBackground) {
self.taskIdentifier =
[[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
[self didExpireInBackground]; // application will retain self until we end the background task
}];
}
#endif
NSURLRequest *urlRequest = [self makeNSURLRequest];
if (![NSURLConnection canHandleRequest:urlRequest]) {
[self failWithError:
[NSError errorWithDomain:FSNConnectionErrorDomain
code:0
userInfo:[NSDictionary dictionaryWithObject:@"request cannot be handled"
forKey:@"description"]]];
return nil;
}
// initWithRequest semantics: url request is deep-copied; connection is started on current thread
// TODO: determine if this deep-copy is problematic for large POST bodies
self.connection = [[NSURLConnection alloc] initWithRequest:urlRequest
delegate:self
startImmediately:NO];
if (!self.connection) {
[self failWithError:
[NSError errorWithDomain:FSNConnectionErrorDomain
code:0
userInfo:[NSDictionary dictionaryWithObject:@"could not establish connection"
forKey:@"description"]]];
return nil;
}
#if FSN_QUEUED_CONNECTIONS
[self.connection setDelegateQueue:[self.class queue]];
#else
[self.connection scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
#endif
[self.connection start];
return self;
}
- (void)cancel {
FSNVerbose(@"%p: cancel", self);
[self.responseStream close];
[self cancelConnection];
[self cleanup]; // release blocks and background task identifier immediately
}
// MARK: background task
#if TARGET_OS_IPHONE
// ending the background task is critical to prevent the os from killing our app,
// and to prevent the application from retaining the request via the expiration handler block
- (void)endBackgroundTask {
if (self.taskIdentifier != UIBackgroundTaskInvalid) {
[[UIApplication sharedApplication] endBackgroundTask:self.taskIdentifier]; // may cause self dealloc
self.taskIdentifier = UIBackgroundTaskInvalid; // zero the property so that we pass the assertion in dealloc
}
}
// called by the expiration handler block
- (void)didExpireInBackground {
ASSERT_MAIN_THREAD; // according to beginBackgroundTaskWithExpirationHandler
[self cancelConnection]; // releases delegate (self)
[self failWithError:
[NSError errorWithDomain:FSNConnectionErrorDomain
code:FSNConnectionErrorCodeExpiredInBackgroundTask
userInfo:[NSDictionary dictionaryWithObject:@"expired in background task" forKey:@"description"]]];
}
#endif
// MARK: progress
- (long long)downloadExpectedBytes {
return self.response.expectedContentLength;
}
- (float)uploadProgress {
if (self.uploadExpectedBytes < 1 || self.uploadProgressBytes > self.uploadExpectedBytes) return -1;
return (float)self.uploadProgressBytes / (float)self.uploadExpectedBytes;
}
- (float)downloadProgress {
if (self.downloadExpectedBytes < 1 || self.downloadProgressBytes > self.downloadExpectedBytes) return -1;
return (float)self.downloadProgressBytes / (float)self.downloadExpectedBytes;
}
- (void)performReportProgress {
[self performSelectorOnMainThread:@selector(reportProgress) withObject:nil waitUntilDone:NO];
}
- (void)reportProgress {
ASSERT_MAIN_THREAD;
[self.blocksLock lock];
if (self.progressBlock) {
self.progressBlock(self);
}
[self.blocksLock unlock];
}
// MARK: request construction
- (NSString *)makeRequestString {
if (self.method != FSNRequestMethodGET || !self.parameters.count) {
return self.url.absoluteString;
}
return [NSString stringWithFormat:@"%@?%@", self.url.absoluteString, self.parameters.urlQueryString];
}
- (NSData*)makePostBodyWithBoundary:(NSString*)boundary {
NSAssert1(self.method == FSNRequestMethodPOST, @"wrong method: %d", self.method);
NSMutableData *data = [NSMutableData data];
NSData *prefix = [[NSString stringWithFormat:@"--%@\r\n", boundary] UTF8Data];
NSData *sep = [@"\r\n" UTF8Data];
for (id key in self.parameters) {
id val = [self.parameters objectForKey:key];
if (![key isKindOfClass:[NSString class]]) {
FSNLogError(@"skipping bad parameter key: key class: %@ key: %@", [key class], key);
NSAssert(0, @"bad parameter key type");
continue;
}
NSString *typeString = nil;
NSString *fileName = nil;
NSData *valData = nil;
if ([val isKindOfClass:[NSString class]] || [val isKindOfClass:[NSNumber class]]) {
// webkit does not specify a type for plain text strings, so we don't either
//valType = @"text/plain; charset=\"UTF-8\"";
valData = [[val description] UTF8Data];
}
else if ([val isKindOfClass:[FSNData class]]) {
typeString = [val mimeTypeString];
valData = [val data];
fileName = [val fileName];
}
else {
FSNLogError(@"skipping bad POST parameter value: key: %@; value class: %@; value: %@",
key, [val class], val);
NSAssert(0, @"bad POST parameter value type");
continue;
}
[data appendData:prefix];
NSString *fileNameClause = fileName ? [NSString stringWithFormat:@"; filename=\"%@\"", fileName] : @"";
[data appendData:
[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"%@\r\n", key, fileNameClause]
UTF8Data]];
if (typeString) {
[data appendData:[[NSString stringWithFormat:@"Content-Type: %@\r\n", typeString] UTF8Data]];
}
[data appendData:sep];
[data appendData:valData];
[data appendData:sep];
}
[data appendData:[[NSString stringWithFormat:@"--%@--\r\n\r\n", boundary] UTF8Data]];
#if FSN_LOG_POST_DATA
FSNErr(@" POST data:\n%@\n", [data debugString]);
#endif
return data;
}
void logParameter(FSNRequestMethod method, id key, id val) {
switch (method) {
#if !FSN_LOG_GET_PARAMETERS
case FSNRequestMethodGET: break;
#endif
#if !FSN_LOG_POST_PARAMETERS
case FSNRequestMethodPOST: break;
#endif
default:
FSNErr(@" %-16s : %@", [[key description] UTF8String], val);
}
}
// creates an NSURLRequest with which to create an NSURLConnection
- (NSURLRequest*)makeNSURLRequest {
NSString *requestString = [self makeRequestString];
NSURL *url = [[NSURL alloc] initWithString:requestString];
NSMutableURLRequest* r = [NSMutableURLRequest requestWithURL:url];
// always pipeline (could be changed to be an ifdef or instance property).
[r setHTTPShouldUsePipelining:YES];
#if FSN_LOG_REQUESTS
FSNLog(@"%@: %@", stringForRequestMethod(self.method), requestString);
[self.parameters enumerateKeysAndObjectsUsingBlock:^(id k, id v, BOOL *stop) {
logParameter(_method, k, v);
}];
#endif
[r setHTTPMethod:stringForRequestMethod(self.method)];
#if FSN_LOG_HEADERS
#define SET_HEADER(k, v) \
FSNErr(@"- header: %-16s : %@", [k UTF8String], v); [r setValue:v forHTTPHeaderField:k];
#else
#define SET_HEADER(k, v) [r setValue:v forHTTPHeaderField:k];
#endif
switch (self.method) {
case FSNRequestMethodGET:
break; // no body
case FSNRequestMethodPOST: {
// decide if this request needs to be multipart
BOOL multipart = NO;
for (id k in self.parameters) {
if ([[self.parameters valueForKey:k] isKindOfClass:[FSNData class]]) {
multipart = YES;
break;
}
};
NSData *body;
NSString *contentType;
if (multipart) {
// choose a random string boundary and hope it never collides with form data
// this is what web browsers do for form requests (we use our own unique boundary)
NSString *boundary = @"--FSN-POST-boundary-wXzBVZAKUhpccuA9";
body = [self makePostBodyWithBoundary:boundary];
contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
}
else { // UTF8, url-encoded body
NSString *s = self.parameters.urlQueryString;
body = [s UTF8Data];
contentType = @"application/x-www-form-urlencoded";
}
NSString *contentLength = [NSString stringWithFormat:@"%lu", (unsigned long)body.length];
SET_HEADER(@"Content-Type", contentType);
SET_HEADER(@"Content-Length", contentLength);
[r setHTTPBody:body];
break;
}
default:
[NSException raise:@"FSNConnectionException" format:@"unknown request method: %d", self.method];
}
// do this last for more readable header logging (so these are grouped with the conditional headers in the switch)
for (NSString* k in self.headers) {
NSString* v = [self.headers objectForKey:k];
SET_HEADER(k, v);
}
return r;
}
@end