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

时间:2015-02-04 23:53:45

标签: ios objective-c nsstring nsdictionary nsurlsession

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

// 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对象存储了一个字典数组,而且我发布的字符串也不能被编码,它必须是一个简单的字符串,所以它在搜索中是可见的如果我手动输入字段。

我的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:";
}
]

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

更新:

目前我正在尝试将字符串发布为:

            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,结果链接应如下所示:

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":""}]'

1 个答案:

答案 0 :(得分:1)

我最后使用的第一个例子是我的实现:

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