NSURLConnection的使用
NSURL *url=[NSURL URLWithString:@"http://www.baidu.com"];
NSURLRequest *request=[NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
if(!connectionError){
NSString *html=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@",html);
}else{
NSLog(@"连接错误: %@",connectionError);
}
}];
NSURLConnection解析json数据
NSURL *url=[NSURL URLWithString:@"http://www.baidu.com"];
NSURLRequest *request=[NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
if(connectionError){
NSLog(@"连接错误: %@",connectionError);
return;
}
NSHTTPURLResponse *httpResponse=(NSHTTPURLResponse *)response;
if(httpResponse.statusCode==200||httpResponse.statusCode==304){
NSError *error;
NSDictionary *json=[NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
if(error){
NSLog(@"解析json出错:%@",error);
return;
}
}else{
NSLog(@"服务器内部错误");
}
}];