使用 NSURLSession 将 NSString 作为 post 方法的主体发送

Send NSString as body of post method using NSURLSession

我正在尝试 post 使用下一个示例将字符串发送到服务器:

// 1
NSURL *url = [NSURL URLWithString:@"YOUR_WEBSERVICE_URL"];
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];

// 2
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
request.HTTPMethod = @"POST";

// 3
NSDictionary *dictionary = @{@"key1": @"value1"};
NSError *error = nil;
NSData *data = [NSJSONSerialization dataWithJSONObject:dictionary 
  options:kNilOptions error:&error];

if (!error) {
 // 4
 NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request
   fromData:data completionHandler:^(NSData *data,NSURLResponse *response,NSError *error) {
   // Handle response here
   }];

   // 5
   [uploadTask resume];
}

不同的是我没有NSDictionary而是一个存储字典数组的NSString对象,还有我post不能编码的字符串它必须是一个简单的字符串,所以如果我手动输入它,它会在搜索字段中可见。

我的 NSString 示例:

[{
    "api_id" = debugger;
    at = "2015-02-05T01:41:13Z";
    oS = IOS;
    ver = "8.10";
    what = "showAdAt: forViewController:";
},
{
    "api_id" = debugger;
    at = "2015-02-05T01:41:13Z";
    oS = IOS;
    ver = "8.10";
    what = "showAdAt: forViewController:";
}
]

在此先感谢您,请耐心等待,因为这是我的第一次 post 尝试。 我在想,如果我首先将 NSString 转换为 NSArray 并将字典作为对象,那么上面的示例应该对我有用。

更新:

目前我正在尝试 post 字符串为:

            NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
            sessionConfiguration.HTTPAdditionalHeaders = @{
                                                           @"Authorization"       : @"CUSTOM AUTHORIZATION THAT I AM USING",
                                                           @"Content-Type"        : @"application/json"
                                                           };

            // Create the session
            // We can use the delegate to track upload progress
            NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration delegate:self delegateQueue:nil];

            // Data uploading task. We could use NSURLSessionUploadTask instead of NSURLSessionDataTask if we needed to support uploads in the background
            NSURL *url = [NSURL URLWithString:@"MY WEBSITE LINK"];
            NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
            request.HTTPMethod = @"POST";            
            //Convert the string to NSData 
   bodyContainerString = @"[{\"api_id\":\"A124\",\"at\":\"2011-04-10T20:09:31Z\",\"os\":\"ANDROID\",\"ver\":\"2.1\",\"what\":\"TEST\",\"value\":\"\"},{\"api_id\":\"A124\",\"at\":\"2011-04-10T20:10:31Z\",\"os\":\"ANDROID\",\"ver\":\"2.1\",\"what\":\"TEST\",\"value\":\"\"}]";
            NSData* jsonData = [bodyContainerString dataUsingEncoding:NSUTF8StringEncoding];
            jsonData = [jsonData subdataWithRange:NSMakeRange(0, [jsonData length] - 1)];

            NSString* newStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

            NSLog(newStr);

            request.HTTPBody = jsonData;
            NSURLSessionDataTask *uploadTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                // Process the response
                NSHTTPURLResponse *httpResp = (NSHTTPURLResponse*) response;
                if (!error && httpResp.statusCode == 201) {
                    //if no error on upload then delete content of plist
                    NSLog(@"Success  on post1");
                }
                 NSLog(@"Success  on post2");
            }];
            [uploadTask resume];

更新 2,结果 link 应如下所示:

curl -X POST  http://MY_LINK/smtg -H 'Authorization: CUSTOM_FIRST_HEADER' -H "Content-Type: application/json" -d '[{"api_id":"A124","at":"2011-04-10T20:09:31Z","os":"ANDROID","ver":"2.1","what":"TEST","value":""},{"api_id":"A124","at":"2011-04-10T20:10:31Z","os":"ANDROID","ver":"2.1","what":"TEST","value":""}]'

我最终使用了我在此处找到的第一个示例是我的实现:

NSURL *url = [NSURL URLWithString:@"MY_LINK/smtg"];


//Create thhe session with custom configuration
NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
sessionConfiguration.HTTPAdditionalHeaders = @{
                                               @"Authorization"       : [NSString stringWithFormat:@"BEARER %@",finalToken],
                                               @"Content-Type"        : @"application/json"
                                               };

NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration];

// 2
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
request.HTTPMethod = @"POST";

// 3

NSError *error = nil;

NSData* jsonData = [bodyContainerString dataUsingEncoding:NSUTF8StringEncoding];


if (!error) {
    // 4
    NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request
                                                               fromData:jsonData completionHandler:^(NSData *data,NSURLResponse *response,NSError *error) {
                                                                   // Handle response here
                                                               }];

    // 5
    [uploadTask resume];
}}