NSURLConnection

网络
NSURLConnection

常用类

lNSURL:请求地址
lNSURLRequest:一个NSURLRequest对象就代表一个请求,它包含的信息有
    一个NSURL对象
    请求方法、请求头、请求体
    请求超时
    … …
lNSMutableURLRequest:NSURLRequest的子类

lNSURLConnection
    负责发送请求,建立客户端和服务器的连接
    发送数据给服务器,并收集来自服务器的响应数据
NSURLConnection_第1张图片
Snip20151017_4.png
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    //1.创建url
    NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login"];
    //2.创建请求(默认发的是GET请求)(如果想发送的是POST请求,需要使用可变请求,并且改变可变请求中的)
    //2.1 NSURLRequest:不可变的请求:无法改变请求中的 请求头, 请求体;
//    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    //2.2 NSMutableURLRequest:可以修改请求中的请求头和请求体信息(一般都用这个);
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //改变请求方法
    request.HTTPMethod = @"POST";
    //改变请求体
    NSString *username = @"520it";
//    防止出现中文无法识别,需要进行转码
    username = [username stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *pwd = @"520it";
    NSString *str = [NSString stringWithFormat:@"username=%@&pwd=%@",username, pwd];
    request.HTTPBody = [str dataUsingEncoding:NSUTF8StringEncoding];
    //3.创建 NSURLConnection(有三种方式)
    //异步
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        //回调block(拿到响应的一些数据)
        NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
        
    }];
    
    //同步
//    两个*代表传入一个指针,系统拿到后可以修改对应地址的值
    NSURLResponse *res = nil;
    NSError *error = [[NSError alloc]init];
    [NSURLConnection sendSynchronousRequest:request returningResponse:&res error:&error];
    
    
    //使用代理
    NSURLConnection *conne = [[NSURLConnection alloc] initWithRequest:request delegate:self];//使用代理

    [NSURLConnection connectionWithRequest:request delegate:self];
    
    NSURLConnection *conne2 = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
}


#pragma mark - 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
{
    
}
  • Posted by .lovepeijun

你可能感兴趣的:(NSURLConnection)