如何在NSMutableRequest中添加请求参数

我创建了一个可变的请求。

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0]; [request setHTTPMethod:@"POST"]; [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; // I want to add a request parameter - Not in the header or body. Add Your code here // [request setHTTPBody:data]; 

任何人请帮助我

希望对你有帮助

 NSString *post=[NSString stringWithFormat:@"data={\"user_id\":\"abc\",\"Method\":\"User_nji_abc\"}"]; NSURL *url=[NSURL URLWithString:YOUR_BASE_URL]; NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]]; NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ; [request setURL:url]; [request setHTTPMethod:@"POST"]; [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; [request setHTTPBody:postData]; NSOperationQueue *queue=[[NSOperationQueue alloc]init]; [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { if ([data length] >0 && error == nil){ dicWholeValue=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error]; NSLog(@"%@",dicWholeValue); } else if ([data length] == 0 && error == nil){ NSLog(@"Nothing was downloaded."); } else if (error != nil){ [[NSOperationQueue mainQueue] addOperationWithBlock:^{ //Do any updates to your label here UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Message" message:@"Could not connect to server." delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil]; [alert show]; alert=nil; NSLog(@"Error happened = %@", error); }]; } }]; 

在您的问题中,您指定了Content-Type of application/json ,因此,如果这是您的服务器所需的,您可能使用NSJSONSerialization方法dataWithJSONObject来构建您将使用setHTTPBody指定的NSData对象。 例如:

 NSDictionary *params = @[@"search" : @"restaurants", @"postal" : @"10003"]; // supply whatever your web service requires NSError *error; NSData *data = [NSJSONSerialization dataWithJSONObject:params options:0 error:&error]; NSAssert(data, @"Unable to serialize JSON: %@", error); [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; [request setHTTPBody:data]; 

但有时,Web服务将返回JSON,但期望请求为application/x-www-form-urlencoded 。 在这种情况下, NSData的格式非常不同。

 NSDictionary *params = @[@"search" : @"restaurants", @"postal" : @"10003"]; // supply whatever your web service requires NSMutableArray *postArray = [NSMutableArray array]; [params enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSString *obj, BOOL *stop) { [postArray addObject:[NSString stringWithFormat:@"%@=%@", key, [self percentEscapeString:obj]]]; }]; NSString *postString = [postArray componentsJoinedByString:@"&"]; NSData *data = [postString dataUsingEncoding:NSUTF8StringEncoding]; [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; [request setHTTPBody:data]; 

你百分比逃脱你的字符串,如下所示:

 - (NSString *)percentEscapeString:(NSString *)string { NSCharacterSet *allowedCharacters = [NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-._~/?"]; return [string stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacters]; } 

(注意,这需要iOS 7或更高版本。如果支持早期iOS版本,则必须执行此类操作 。)

最重要的是,在我们进一步建议您之前,我们需要有关Web服务API需要的更多信息。