Since you did not mention about what kind of body type you want to use this example shows you how to post multipart/form-data request.
-(NSString *)generateRandomBoundryString {
CFUUIDRef UUID = CFUUIDCreate(kCFAllocatorDefault);
CFStringRef UUIDString = CFUUIDCreateString(kCFAllocatorDefault,UUID);
NSString *aNSString = (__bridge NSString *)UUIDString;
CFRelease(UUID);
CFRelease(UUIDString);
return aNSString;
}
-(IBAction)Login:(id)sender {
NSString *bndry = [self generateRandomBoundryString];
NSString *contentType = [[NSString alloc] initWithString:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", bndry]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://grouporder.site90.net/test.php"]];
[request setHTTPMethod:@"POST"];
[request setValue: contentType forHTTPHeaderField:@"Content-Type"];
//form-data block
NSMutableData *requestBody = [NSMutableData data];
[requestBody appendData:[[NSString stringWithFormat:@"
--%@
", bndry] dataUsingEncoding:NSUTF8StringEncoding]];
[requestBody appendData:[[NSString stringWithFormat:@"%@=%@", @"name", @"John"] dataUsingEncoding:NSUTF8StringEncoding]];
[requestBody appendData:[[NSString stringWithFormat:@"
--%@
", bndry] dataUsingEncoding:NSUTF8StringEncoding]];
[requestBody appendData:[[NSString stringWithFormat:@"%@=%@", @"password", @"myPassword"] dataUsingEncoding:NSUTF8StringEncoding]];
[requestBody appendData:[[NSString stringWithFormat:@"
--%@
", bndry] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:requestBody];
//form-data block
// NSURLConnection Asynchronous Block
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *rspreportStatus, NSData *datareportStatus, NSError *e)
{
if (e == nil)
{
// If all ok you can processes response data here.
}
else {
NSLog(@"%@", e.localizedDescription);
}
}];
}
If body is application/x-www-form-urlencoded
you should change Content-Type value like this.
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
and replace //form-data block block with this.
[requestBody appendData:[[NSString stringWithFormat:@"name=%@&password=%@", @"John", @"myPassword"] dataUsingEncoding:NSUTF8StringEncoding]];
@"John"
and @"myPassword"
has to be URL encoded.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…