Wednesday, May 1, 2013

NSMutableURLRequest setURL example ios


setURL:

Sets the URL of the receiver
- (void)setURL:(NSURL *)theURL
Parameters of [NSMutableURLRequest setURL]
theURL
The new URL.
Example of [NSMutableURLRequest setURL]
NSString *post = [NSString stringWithFormat:@"username=%@&password=%@",username.text,password.text];
NSLog(@"%@",post);
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:@" server link here"]]];
[request setHTTPMethod:@"POST"];
NSString *json = @"{}";
NSMutableData *body = [[NSMutableData alloc] init];
[request setHTTPBody:
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Current-Type"];
[request setHTTPBody:postData];
//get response
NSHTTPURLResponse* urlResponse = nil;  
NSError *error = [[NSError alloc] init];  
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];  
NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(@"Response Code: %d", [urlResponse statusCode]);

if ([urlResponse statusCode] >= 200 && [urlResponse statusCode] < 300) 
{
    NSLog(@"Response: %@", result);
}
Example of [NSMutableURLRequest setURL]
NSString *getString = [NSString stringWithFormat:@"parameter=%@",yourvalue];
NSData *getData = [getString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

NSString *getLength = [NSString stringWithFormat:@"%d", [getData length]];

NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];

[request setURL:[NSURL URLWithString:@"https:yoururl"]];

[request setHTTPMethod:@"GET"];

[request setValue:postLength forHTTPHeaderField:@"Content-Length"];

[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

[request setHTTPBody:getData];

self.urlConnection = [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];

NSAssert(self.urlConnection != nil, @"Failure to create URL connection.");

// show in the status bar that network activity is starting
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;