iOS 网络的请求

既然上篇文章说到了网络的判断,那这篇文章就来讲一下网络的请求吧,如有不对,敬请纠正微笑
请求方式:GET、POST、SOAP

GET->构建不可变的请求对象

1.构建网络资源路径
NSURL *url = [NSURL URLWithString:@"http://www.baidu.com"];


2.构建请求对象
NSURLRequest *request = [NSURLRequest requestWithURL:url];


3.1 构建连接对象(同步:会造成界面假死)
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];


3.2 构建连接对象(异步:多线程)推荐用法
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[conn start];


实现NSURLConnectionDataDelegate协议方法


已经接收到响应头
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response


开始接收数据:可能调用多次
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data


连接失败
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error


连接已完成
- (void)connectionDidFinishLoading:(NSURLConnection *)connection


POST->构建可变的请求对象
1 设置请求方式
[request setHTTPMethod:@"POST"];


2 设置请求内容
NSString *body = [NSString stringWithFormat:@"mobileCode=%@&userID=",self.txtPhone.text];
NSData *bodyData = [body dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:bodyData];


3 设置请求头
NSString *bodyLen = [NSString stringWithFormat:@"%i",[bodyData length]];
[request addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request addValue:bodyLen forHTTPHeaderField:@"Content-Length"];

构建连接对象同上,就不赘述来哈!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值