今天和后台调试结果,因为他那边要求传的是json字符串。而第三方库AFNetworking不懂为啥,传给后台的字符串老是有问题,所以我自己又重新去写NSURLSession,结果因为我挺久没自己写NSURLSession,没写完全,少了请求头(默认是表格),导致后台那边老是读取不到我发送的东西。
[request addValue:@"application/json" forHTTPHeaderField:@"content-type"];//要记得加这个content-type
简单的写下吧,因为毕竟NSURLSession现在用的很多了,但一些东西还是容易被人忽略
NSURL *url = [NSURL URLWithString:urlStr];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setHTTPMethod:@"POST"];
[request addValue:@"application/json" forHTTPHeaderField:@"content-type"];//要记得加这个content-type
NSData *data= [params dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:data];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (!error) {
NSLog(@"请求成功");
if (data.length > 0) {
[self connectionSuccess:data ConnectionBlock:block];
}
}else
{
NSLog(@"请求失败 error == %@",error);
[self connectionFail:error ConnectionBlock:block];
}
if (data.length > 0) {//防止后台返回空的,导致写入空的导致崩溃
NSLog(@"dataStr == %@",[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);
}
}];
[task resume];
参考文献:
iOS - 发送请求NSURLSession
网友评论