iPhone: Testing Browser (HTTP Headers)
Here is the code i am currently using:
@implementation SubmitAndLaunch
@synthesize postVariables;
@synthesize postDestination;
@synthesize redirectedURL;
- (void)connectAndSubmit {
if (postVariables == nil | postDestination == nil) {
// Die
[NSException raise:@"InvalidVarsDest" format:@"The Variables or Destination were not defined"];
}
NSData *postData = [postVariables dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:postDestination]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPShouldHandleCookies:YES];
[request setValue:@"text/html,application/xhtml+xml,application/xml;q=0.9, /;q=0.8" forHTTPHeaderField:@"Accept"];
[request setHTTPBody:postData];
NSURLConnection *conn=[[NSURLConnection alloc] initWithRequest:request delegate:self];
[conn start];
}
- (id)initWithVariables:(NSString *)vars Destination:(NSString *)dest {
self = [super init];
if (self != nil) {
postVariables = vars;
postDestination = dest;
[self connectAndSubmit];
}
return self;
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
redirectedURL = [response URL];
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
NSDictionary *header = [httpResponse allHeaderFields];
NSMutableArray *ourCookieArray = [NSHTTPCookie cookiesWithResponseHeaderFields:header forURL:redirectedURL];
NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
[storage setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways];
for (int i=0; i< [ourCookieArray count]; i++) {
[storage setCookie:[ourCookieArray objectAtIndex:i]];
}
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:[redirectedURL absoluteString]]];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
}
- (void)dealloc{
[redirectedURL dealloc];
[postVariables dealloc];
[postDestination dealloc];
[super dealloc];
}
@end
15in MBP C2D, Mac OS X (10.4.9)