Skip to content

Instantly share code, notes, and snippets.

@marceloandrader
Created March 23, 2010 22:00
Show Gist options
  • Save marceloandrader/341726 to your computer and use it in GitHub Desktop.
Save marceloandrader/341726 to your computer and use it in GitHub Desktop.
+ (Response *)sendRequest:(NSMutableURLRequest *)request withUser:(NSString *)user andPassword:(NSString *)password {
//lots of servers fail to implement http basic authentication correctly, so we pass the credentials even if they are not asked for
//TODO make this configurable?
NSURL *url = [request URL];
if(user && password) {
NSString *authString = [[[NSString stringWithFormat:@"%@:%@",user, password] dataUsingEncoding:NSUTF8StringEncoding] base64Encoding];
[request addValue:[NSString stringWithFormat:@"Basic %@", authString] forHTTPHeaderField:@"Authorization"];
NSString *escapedUser = (NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
(CFStringRef)user, NULL, (CFStringRef)@"@.:", kCFStringEncodingUTF8);
NSString *escapedPassword = (NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
(CFStringRef)password, NULL, (CFStringRef)@"@.:", kCFStringEncodingUTF8);
NSMutableString *urlString = [NSMutableString stringWithFormat:@"%@://%@:%@@%@",[url scheme],escapedUser,escapedPassword,[url host],nil];
if([url port]) {
[urlString appendFormat:@":%@",[url port],nil];
}
[urlString appendString:[url path]];
if([url query]){
[urlString appendFormat:@"?%@",[url query],nil];
}
[request setURL:[NSURL URLWithString:urlString]];
[escapedUser release];
[escapedPassword release];
}
[self logRequest:request to:[url absoluteString]];
ConnectionDelegate *connectionDelegate = [[[ConnectionDelegate alloc] init] autorelease];
[[self activeDelegates] addObject:connectionDelegate];
NSURLConnection *connection = [[[NSURLConnection alloc] initWithRequest:request delegate:connectionDelegate startImmediately:NO] autorelease];
connectionDelegate.connection = connection;
//use a custom runloop
static NSString *runLoopMode = @"com.yfactorial.objectiveresource.connectionLoop";
[connection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:runLoopMode];
[connection start];
while (![connectionDelegate isDone]) {
[[NSRunLoop currentRunLoop] runMode:runLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:.3]];
}
Response *resp = [Response responseFrom:(NSHTTPURLResponse *)connectionDelegate.response
withBody:connectionDelegate.data
andError:connectionDelegate.error];
[resp log];
[activeDelegates removeObject:connectionDelegate];
//if there are no more active delegates release the array
if (0 == [activeDelegates count]) {
NSMutableArray *tempDelegates = activeDelegates;
activeDelegates = nil;
[tempDelegates release];
}
return resp;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment