以下实例通过POST方法提交数据并返回结果
@try { NSError *error; NSURL *url = [NSURL URLWithString:@http://www.corp.com/info.aspx]; NSMutableDictionary *dic =" [[NSMutableDictionary" alloc] init]; [dic setValue:@"14" forKey:@"type"]; [dic setValue:@"POST" forKey:@"method"]; [dic setValue:@"1" forKey:@"siteid"]; NSString *myBounds = [[NSString alloc] initWithString:@"test"]; NSMutableURLRequest *myRequest = [NSMutableURLRequest requestWithURL:url]; NSString *myContent = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",myBounds]; [myRequest setValue:myContent forHTTPHeaderField:@"content-type"]; [myRequest setHTTPMethod:@"POST"]; [myRequest setHTTPBody:[self createFormData:dic withBoundary:myBounds]]; NSURLResponse *response; NSData *myReturn = [NSURLConnection sendSynchronousRequest:myRequest returningResponse:&response error:&error]; NSString *str = [[NSString alloc] initWithData:myReturn encoding:NSUTF8StringEncoding]; } @catch (NSException *exception) { // } @finally { // }
以上方法中用到的createFormData方法:
- (NSData*)createFormData:(NSDictionary *)myDictionary withBoundary:(NSString *)myBounds{ NSMutableData *myReturn = [[NSMutableData alloc] initWithCapacity:10]; NSArray *formKeys = [myDictionary allKeys]; for(int i=0;i<[formKeys count];i++){ [myReturn appendData:[[NSString stringWithFormat:@"--%@\n",myBounds] dataUsingEncoding:NSUTF8StringEncoding]]; [myReturn appendData:[[NSString stringWithFormat:@"content-disposition: form-data; name=\"%@\"\n\n%@\n", [formKeys objectAtIndex:i], [myDictionary valueForKey:[formKeys objectAtIndex:i]]] dataUsingEncoding:NSUTF8StringEncoding]]; } [myReturn appendData:[[NSString stringWithFormat:@"--%@--\n", myBounds] dataUsingEncoding:NSUTF8StringEncoding]]; return myReturn; }