对于网络请求类型有两种形式
GEt、POST
区别:
get操作简单,所有参数直接写到地址中
post操作复杂,将参数和地址分开来写
get请求安全性不如post形式
get请求URL地址长度有限:只支持最多255个字符,post请求可以传递大量数据:上传没有大小限制。
网络连接的类型分为同步连接和异步连接
同步连接:UI(UserInterface)冻结,用户体验差。
异步连接:UI(UserInterface)不冻结,用户体验好。用代理可后台操作。
同步异步下载示例:
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@property (retain, nonatomic) UIImageView *imgV;
@end
#import "ViewController.h"
#define URL01 @"http://ww4.sinaimg.cn/bmiddle/b825b757jw1eaw8xm5v7hj20d70j9tad.jpg"
#define URL02 @"http://ww3.sinaimg.cn/bmiddle/c8dc68bajw1eaw9bpj6kfj20by0bymyw.jpg"
@interface ViewController ()
@end
@implementation ViewController
- (void)sendSyn:(NSString *) urlStr
{
/*
同步连接:
1.创建NSURL
2.通过NSURL创建NSURLRequest
3.建立NSURLConnection发送同步请求
4.数据完成之后进行处理
*/
NSString *str = URL01;
NSURL *url = [NSURL URLWithString:str];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
NSURLResponse *response = nil;
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&error];
UIImage *img = [UIImage imageWithData:data];
self.imgV.image = img;
}
- (void)sendAsyn:(NSString *)urlStr
{
/*
同步连接:
1.创建NSURL
2.通过NSURL创建NSURLRequest
3.建立NSURLConnection发送异步请求
4.数据完成之后进行处理
*/
NSString *str = URL02;
NSURL *url = [NSURL URLWithString:str];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init ]completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
UIImage *img = [UIImage imageWithData:data];
self.imgV.image = img;
}];
}
- (void)viewDidLoad
{
[super viewDidLoad];
//创建一个UIImageView框架用于放图片
self.imgV = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 300)];
//测试是否创建成功 设置它的颜色为红色
self.imgV.backgroundColor = [UIColor redColor];
//将UIImageView加入到父视图
[self.view addSubview:self.imgV];
//创建按钮
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
//设置按钮的位置及大小
btn.frame = CGRectMake(55, 320, 100, 44);
//设置按钮标题
[btn setTitle:@"同步下载" forState:UIControlStateNormal];
//设置按钮的点击事件
[btn addTarget:self action:@selector(sendSyn:) forControlEvents:UIControlEventTouchUpInside];
//测试方法
// [self sendSyn:URL01];
[self.view addSubview:btn];
UIButton *btn1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn1.frame = CGRectMake(180, 320, 100, 44);
[btn1 setTitle:@"异步下载" forState:UIControlStateNormal];
[btn addTarget:self action:@selector(sendAsyn:) forControlEvents:UIControlEventTouchUpInside];
// [self sendAsyn:URL02];
[self sendAsyn:@""];
[self.view addSubview:btn1];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end