通过post方法通过HTTP请求发送JSON

时间:2015-01-11 01:20:23

标签: ios json xmlhttprequest

我试图通过HTTP请求发送JSON:

这是我的代码:

NSString* locations = [kBaseURL stringByAppendingPathComponent:kLocations];

BOOL isExistingLocation = location._id != nil;

NSString *urlStr = isExistingLocation ? [locations stringByAppendingPathComponent:location._id] : locations;
NSURL* url = [NSURL URLWithString:urlStr]; //1

NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";


NSData* data = [NSJSONSerialization dataWithJSONObject:[location toDictionary] options:0 error:NULL]; //3
request.HTTPBody = data;

[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; //4

NSURLSessionConfiguration* config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession* session = [NSURLSession sessionWithConfiguration:config];

NSURLSessionDataTask* dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { //5
    if (!error) {
        NSLog(@"%@", response.description);

        NSArray* responseArray = @[[NSJSONSerialization JSONObjectWithData:data options:0 error:NULL]];
       [self parseAndAddLocations:responseArray toArray:self.objects];
    }
}];
[dataTask resume];

这是我试图发送的字典......

http://www.imageupload.co.uk/image/5YUE

编辑:我将服务器配置为返回收到的HTTPBody,返回

{}

0 个答案:

没有答案