【问题标题】:Send NSString as body of post method using NSURLSession使用 NSURLSession 将 NSString 作为 post 方法的主体发送
【发布时间】:2015-02-04 23:53:44
【问题描述】:

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

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

【问题讨论】:

  • 这里不太清楚你在问什么。您是说顶部代码块是您找到的一些示例代码,而底部代码块是您要发布的 NSString 的内容,而不是示例中的 NSDictionary
  • request.HTTPBody = [yourString dataUsingEncoding:NSUTF8StringEncoding];怎么样
  • @midhun-mp 我刚刚上传了我正在使用的代码
  • 所以你想发出一个 HTTP POST 请求,而 POST 就像 myKey=aJSONString?

标签: ios objective-c nsstring nsdictionary nsurlsession


【解决方案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];
}}

【讨论】:

    猜你喜欢
    • 2013-10-06
    • 2017-01-25
    • 1970-01-01
    • 2018-10-07
    • 1970-01-01
    • 2013-04-07
    • 2018-01-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多