ios - 调用内容类型为 : application/x-www-form-urlencoded and Authorization using NSURLSession 的 REST API

标签 ios nsurlsession

如何使用 NSURLSession 调用具有 Content-Type: application/x-www-form-urlencoded 和授权的 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];

}

最佳答案

您需要将 header 键和值添加到 NSURLSessionConfiguration:

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

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

另请注意,您提交的值(“TEST IOS”和“IOS TYPE”)当前未经过 Url 编码。

使用 stringByAddingPercentEncodingWithAllowedCharacters 对它们进行编码:

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

关于ios - 调用内容类型为 : application/x-www-form-urlencoded and Authorization using NSURLSession 的 REST API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34981247/

相关文章:

iphone - iPhone 时间戳(NSDate)相对于全局时钟的准确性?

nsurlrequest - NSURLRequest 超时值会覆盖 NSURLSessionConfiguration timeoutIntervalForRequest 值吗?

ios - 如何在没有信标标识符的情况下找到 iBeacon?

ios - 使用自定义 UIWindow 时第一响应者的问题

iOS:AFNetworking 多重下载。请求操作超时

ios - 当用户关闭应用程序且任务仍处于事件状态时,NSURLSessionDownloadTask 不会删除文件

ios - 用 NSURLSession 替换 NSURLConnection

ios - NSURLSessionDownloadTask cancelByProducingResumeData返回null

ios - 核心数据迁移失败

ios - 添加到管理对象有序集