在NSURLSession中,HTTPBody必须是NSData吗?

时间:2016-09-29 03:18:26

标签: ios nsurlsession afnetworking-3

当我使用AFNetworking发布参数NSMutableDictionary时,此请求已成功。

但是当我使用NSURLSession时,self.request!.HTTPBody必须是NSData,因此请求失败。

如何使用NSURLSession使请求成功?

postDict[@"jgId"] = "1000000000";
[manager GET:SELECTDEPART parameters:postDict success:^(AFHTTPRequestOperation *operation, id responseObject) {

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
  NSLog(@"-----%@", error);
}];

//use  NSData

NSJSONSerialization.dataWithJSONObject(postDict, options: NSJSONWritingOptions.PrettyPrinted)

请帮帮我。

3 个答案:

答案 0 :(得分:0)

let params = ["jgId": "1000000000"]
let data = try? JSONSerialization.data(withJSONObject: params, options: [JSONSerialization.WritingOptions(rawValue: 0)])

var request = URLRequest(url: URL(string: "https://my-url.com")!, cachePolicy: .returnCacheDataElseLoad, timeoutInterval: 30)
request.httpMethod = "POST"
request.httpBody = data
request.allHTTPHeaderFields = [:]

URLSession.shared.dataTask(with: request) { (data, response, error) in

}

答案 1 :(得分:0)

对于NSURLSession you need NSData,你是对的。

但是你可以使用NSKeyedArchiver轻松convert an NSDictionary to NSData

答案 2 :(得分:0)

您正在使用GET方法从服务器请求数据,因此请求HTTPBody数据不会发送您的参数。通过请求网址,您的参数很简单。

有问题您有SELECTDEPART作为请求的基本网址,postDict作为参数。以下代码使用NSURLSession通过GET

发出parameters请求
// get request URL from base URL and params
NSURLComponents *components = [NSURLComponents componentsWithString:@"http://stackoverflow.com"]; // some thing like SELECTDEPART in your question
NSDictionary *params = @{ @"q": @"ios", @"count": @"10" };  // params of request like your postDict

NSMutableArray *queryItems = [NSMutableArray array];
for (NSString *key in params.allKeys) {
    [queryItems addObject:[NSURLQueryItem queryItemWithName:key value:params[key]]];
}
components.queryItems = queryItems;
NSURL *url = components.URL;
// create request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
request.HTTPMethod = @"GET";

// data task with NSURLSession
NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
    if (!error) {
        // parse your data here
    } else {
        // handle error here
    }
}];
[task resume];