同步,异步
同步阻塞主线程,异步开辟子线程进行,需要设置代理遵守协议里的方法
遵守的协议:
<NSURLConnectionDataDelegate,NSURLConnectionDelegate>
//接收数据
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
//完成加载
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
//错误信息
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
get请求:
[NSURLConnection connectionWithRequest:requset delegate:self];
post请求:
requeset.HTTPMethod = @"post";//请求类型
requeset.HTTPBody = data;//data是拼接的数据通过(键=值&)
[NSURLConnection connectionWithRequest:requeset delegate:self];//同样实现协议方法
使用JSON解析:(返回的就是解析后的对象,一般是字典或者数组)
id object = [NSJSONSerialization JSONObjectWithData:_recivieData options:NSJSONReadingMutableLeaves error:&error];
补充:使用post请求的话接收完以后需要将全局变量的NSMutableData清空再初始化,不然再次请求无法获取数据:
[_recivieData release];
_recivieData = [[NSMutableData alloc]init];