网络请求常用类
NSURL ---请求地址
NSURLRequest ---GET请求使用
NSMutableURLRequest ---POST请求使用
NSURLConnection ---连接 发送NSURLRequest对象中的数据并收集来自服务器的响应
代理方法 不建议用
NSURLConnectionDataDelegate
//服务器开始返回数据
-(void)connection:didReceiveResponse:
//收到服务器返回的数据,本方法会被调用多次
-(void)connection:didReceiveData:
//数据接收完毕,做数据的最后处理
-(void)connectionDidFinishLoading:
//网络连接错误
-(void)connection:didFailWithError:
//发送数据给服务器,POST请求使用次方法
-(void)connection:didSendBodyData:totalBytesWritten:totalBytesExpectedToWrite:
使用post 同步发送请求
-(void)login
{
NSString * urlString = [NSString stringWithFormat:@"http://192.168.1.1/login.php"];
NSURL * url = [NSURL URLWithString:urlString];
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];
//第一个参数url 缓存策略 超时时长
NSURLRequest * request1 = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:2.0f];
//网络访问超时时间
[request setTimeoutInterval:2.0f];
//默认是get
[request setHTTPMethod:@"POST"];
NSString * bodyStr = [NSString stringWithFormat:@"username=%@&password=%@",userName,password];
NSData * body = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:body];
//同步请求
NSURLResponse * response = nil;
NSError * error = nil;
NSData * data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
/*
1、接受到数据,表示工作正常
2、没有接受到数据,但是error为nil 表示接收到空数据
3、error不为空 表示请求出错
*/
if(data != nil)
{
NSString * str = [[NSString alloc]initWithData:data encoding :NSUTF8StringEncoding];
NSLog(@"%@",str);
}else if(data ==nil &&error ==nil)
{
NSLog(@"接收到空数据");
}else
{
NSLog(@"%@",error.localizedDescription);
}
}
异步请求
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue]completionHandler:^(NSURLResponse * response, NSData* data,NSError *error)
{
if(data != nil)
{
NSString * str = [[NSString alloc]initWithData:data encoding :NSUTF8StringEncoding];
NSLog(@"%@",str);
}else if(data ==nil &&error ==nil)
{
NSLog(@"接收到空数据");
}else
{
NSLog(@"%@",error.localizedDescription);
}
}