当我使用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)
请帮帮我。
答案 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];