iOS 原生HTTP操作NSURLRequest用法記錄
2015年12月14日iOS Standard
平時做項目太過依賴封裝好的類庫,網絡模塊一直使用AFNETWORKING;一直沒有仔細了解其內部的實現,現在簡單的了解NSURLRequest的使用。
NSURLRequest基本的異步POST示例:JSON格式數據
NSURL *url = [NSURL URLWithString:@”http://xxxx.com/xxx“];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:15.0f];
[req setHTTPMethod:@”POST”];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params
options:NSJSONWritingPrettyPrinted // Pass 0 if you don’t care about the readability of the generated string error:nil];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSData *postDatas = [NSData dataWithBytes:[jsonString UTF8String] length:[jsonString length]];
[req setValue:@”application/json” forHTTPHeaderField:@”Content-Type”]; //设置发送数据的格式
[req setValue:@”application/json” forHTTPHeaderField:@”Accept”]; //设置预期接收数据的格式
[req setHTTPBody:postDatas];
NSOperationQueue *queue = [NSOperationQueue mainQueue];
[NSURLConnection sendAsynchronousRequest:req queue:queue completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
ion JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
NSLog(@”%@”,dic);
}];
发表评论或回复