使用NSURLSession调用具有Content-Type:application / x-www-form-urlencoded和Authorization的REST API

时间:2016-01-24 20:45:23

标签: ios nsurlsession

如何使用NSURLSession调用具有Content-Type:application / x-www-form-urlencoded和Authorization的REST API

Request Url: https://<host>:<port>/signUp
Request Method: POST
Content-Type: application/x-www-form-urlencoded
Accept: application/json 
Authorization: MPS ABCDEFGH

输入参数

msg={
    "Data": {
        "ID": "10",
        "req": "HDFC",
        "TypeId": "180",
        "sd": "MNO"
    },
    "Cde": "CODE",
    "Key": "KEY",
    "bcCode": null,
    "MCcode": null,
    "PinCode": null
}

到目前为止我尝试了什么

-(void)myCallApi
{
 NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];


    NSString *urlstring=[NSString stringWithFormat:@"https://<host>:<port>/signUp"];
    NSURL *url = [NSURL URLWithString:urlstring];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                           cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                       timeoutInterval:60.0];

    [request addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request addValue:@"application/json" forHTTPHeaderField:@"Accept"];
    NSString *authValue = [NSString stringWithFormat:@"MPS ABCDEFGH"];
    [request setValue:authValue forHTTPHeaderField:@"Authorization"];

    [request setHTTPMethod:@"POST"];
     NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys: @"TEST IOS", @"name",
     @"IOS TYPE", @"typemap",
     nil];
     NSData *postData = [NSJSONSerialization dataWithJSONObject:mapData options:0 error:&error];
     [request setHTTPBody:mapData];
        NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

        NSString* responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

        if([responseString rangeOfString:@"nil"].location != NSNotFound)
        {
            NSString * newResponse =  [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];

            responseString = newResponse;
        }

        NSLog(@"%@",responseString);
        NSLog(@"response %@",response);
        NSLog(@"error %@",error);


    }];

    [postDataTask resume];

}

1 个答案:

答案 0 :(得分:1)

您需要将标题键和值添加到NSURLSessionConfiguration

configuration.HTTPAdditionalHeaders["Content-Type"] = @"application/x-www-form-urlencoded";

对任何其他HTTP标头(在您的情况下为授权)执行相同操作。

另请注意,您提交的值(&#34; TEST IOS&#34;和&#34; IOS TYPE&#34;)目前不是Url编码。

使用stringByAddingPercentEncodingWithAllowedCharacters对其进行编码:

[@"TEST IOS" stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];