首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用NSString发送NSURLSession作为post方法的主体

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

Stack Overflow用户
提问于 2015-02-04 23:53:44
回答 1查看 1.7K关注 0票数 3

我试图使用下面的示例将字符串发送到服务器:

代码语言:javascript
运行
复制
// 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示例:

代码语言:javascript
运行
复制
[{
    "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,那么上面的示例应该适用于我。

更新:

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

代码语言:javascript
运行
复制
            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,生成的链接应该如下所示:

代码语言:javascript
运行
复制
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":""}]'
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-02-05 08:52:39

最后,我使用了我在这里找到的第一个示例--我的实现:

代码语言:javascript
运行
复制
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];
}}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28333814

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档