//同步网络通信
//1.构建URL地址
NSURL *url = [NSURL URLWithString:@"http://piao.163.com/m/cinema/list.html?app_id=1&mobileType=iPhone&ver=2.6&channel=appstore&deviceId=9E89CB6D-A62F-438C-8010-19278D46A8A6&apiVer=6&city=110000"];
//2.构建请求NSURLRequest
// NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url
// cachePolicy:NSURLRequestReturnCacheDataElseLoad
// timeoutInterval:60];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//设置请求方式(get or post)
[request setHTTPMethod:@"GET"];
//设置超时时间
[request setTimeoutInterval:60];
//设置请求头信息
[request setValue:@"gzip" forHTTPHeaderField:@"Accept-Encoding"];
// [request addValue:<#(NSString *)#> forHTTPHeaderField:<#(NSString *)#>]
// [request setAllHTTPHeaderFields:<#(NSDictionary *)#>]
//设置请求体(post)
// [request setHTTPBody:<#(NSData *)#>];
//设置缓存
[request setCachePolicy:NSURLRequestReturnCacheDataElseLoad];
//3.构建NSURLCollection,发送网络请求
NSHTTPURLResponse *response = nil;
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&error];
//4.获取数据显示
//将data转为字符串
NSString *jsonData = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
self.textView.text = jsonData;
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSLog(@"数据结果:%@",dic);
//5.获取响应信息
NSInteger statusCode = response.statusCode;
NSDictionary *allHeaderFields = response.allHeaderFields;
NSLog(@"statusCode:%ld",statusCode);
NSLog(@"allHeaderFields: %@",allHeaderFields);
原文地址:http://10554237.blog.51cto.com/10544237/1693316