How to add request Parameters in NSMutableRequest

2020-08-01 11:47发布

问题:

I Have created a mutable request .

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];

Any one please help me

回答1:

HOPE THIS WILL HELP YOU

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);

        }];

    } }];


回答2:

In your question, you specified a Content-Type of application/json, so if that's what your server requires, you'd probably use NSJSONSerialization method dataWithJSONObject to build that NSData object that you'll specify with setHTTPBody. For example:

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];

But sometimes, a web service will return JSON, but will expect the request to be application/x-www-form-urlencoded. In such case, the format of the NSData is very different.

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];

Where you percent escape your string like so:

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

(Note, that requires iOS 7 or later. If supporting earlier iOS versions, you have to do something like this.)

Bottom line, we need more information about precisely what the web service API requires before we can advise you further.