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"];

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章