既然上篇文章说到了网络的判断,那这篇文章就来讲一下网络的请求吧,如有不对,敬请纠正
请求方式: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"];
构建连接对象同上,就不赘述来哈!