//同步请求可以一次性的接收所有数据 但是在主线程中完成 会阻塞主线程
-(void)sendRequestTongbu
{
//创建一个NSSring类型的URL连接字符串
NSString *urlString = @"http://www.apple.com";
//转换成NSURL类型
NSURL *url = [NSURL URLWithString:urlString];
//实例化一个request,把URL对象赋值到NSURLRequest对象中
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSError *error = nil;
//获得数据
NSData *data = [NSURLConnectionsendSynchronousRequest:request returningResponse:nilerror:&error];
//在下载完数据后,一般都需要做data是否为空的判断
if (data == nil)
{
NSLog(@"send request failed");
return;
}
NSString *str = [[NSStringalloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@",str);
}
//异步请求 需要在代理中接收数据 不会阻塞当前线程 记得加上<NSURLConnectionDataDelegate>
-(void)senderRequestYibu
{
NSString *urlString = @"http://www.cnblogs.com/chenhaosuibi/";
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *resquest = [NSURLRequest requestWithURL:url];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:resquest delegate:self];
if (connection) {
NSLog(@"链接成功");
}
else
{
NSLog(@"链接失败");
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(@"收到响应,请求成功");
NSLog(@"%@",response);
// 可以在里面判断返回结果, 或者处理返回的http头中的信息
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSLog(@"收到了Data");
NSString *dataStr = [[NSStringalloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"dataStr = %@",dataStr);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"全部接受完数据后触发");
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"链接出错");
NSLog(@"%@",error);
}