如何使用NSURLsession发布NSdictionary?

时间:2015-07-29 21:14:14

标签: ios post nsdictionary nsurlsession

我想将NSdictionary发布到我的后端服务器。我使用以下代码:

 // 1
    NSURL *url = [NSURL URLWithString:@"http://hyper-recipes.herokuapp.com/recipes"];
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:config];

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

    // 3
    NSString *recipes_name= @"Yazdi Cakes";
    int recipes_difficulty=2;
    NSDictionary *recipesparameter=@{@"recipe": @{@"name": recipes_name, @"difficulty": [NSNumber numberWithInt:recipes_difficulty]}};

    NSError *error = nil;
    NSData *data = [NSJSONSerialization dataWithJSONObject:recipesparameter
                                                   options:kNilOptions error:&error];


    if (!error) {
        // 4
        NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request
                                                                   fromData:data completionHandler:^(NSData *data,NSURLResponse *response,NSError *error) {
                                                                       // Handle response here
                                                                       NSLog(@"responce is %@",response);

                                                                   }];

        // 5
        [uploadTask resume];
    }

代码正在运行,但它不会向服务器发布任何内容。你知道为什么吗?我也尝试检查NSURLresponce,这是响应:

{ status code: 422, headers {
    "Cache-Control" = "no-cache";
    Connection = "keep-alive";
    "Content-Length" = 89;
    "Content-Type" = "application/json; charset=utf-8";
    Date = "Thu, 30 Jul 2015 12:53:37 GMT";
    Server = "WEBrick/1.3.1 (Ruby/2.0.0/2015-04-13)";
    Via = "1.1 vegur";
    "X-Content-Type-Options" = nosniff;
    "X-Frame-Options" = SAMEORIGIN;
    "X-Request-Id" = "569db35e-9420-4e5e-b52b-7d650631b33e";
    "X-Runtime" = "0.010962";
    "X-Ua-Compatible" = "chrome=1";
    "X-Xss-Protection" = "1; mode=block";
} }

1 个答案:

答案 0 :(得分:0)

在我看来,您应该将data设置为您的请求的HTTPBody并创建常规数据任务,如下所示:

if (data) {
    request.HTTPBody = data;
    // 4
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
                                                completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                                      // Handle response here
                                                                      NSLog(@"response is %@",response);
                                                                  }];

    // 5
    [dataTask resume];
}