首页 > 技术文章 > 【iOS系列】-iOS开发,GET,POST请求使用

fengtengfei 2015-04-21 22:54 原文

【iOS系列】-iOS开发,GET,POST请求使用

步骤:

1:实例化URL(网络资源)

2:根据URL建立URLRequest(网络请求)
默认为GET请求;
对于POST请求,需要创建请求的数据体

3:利用URLConnection发送网络请求(建立连接)

NSURLConnection的同异请求(网络中一般使用异步请求,同步会阻塞主线程):

同步请求: sendSynchronousRequest:returningResponse:error:

异步请求: sendAsynchronousRequest:queue: completionHandler:

//POST实例

-(void)methodPost
{
    // 1. 实例化URL
    NSURL *url = [NSURL URLWithString:@"XXXXXXX"];
    // 2. 建立URLRequest
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    // 默认就是GET请求
    request.HTTPMethod = @"POST";
    // 数据体
    NSString *str = [NSString stringWithFormat:@"username=%@&password=%@", userName, userPwd];
    // 将字符串转换成数据
    request.HTTPBody = [str dataUsingEncoding:NSUTF8StringEncoding];
    
    // 3.利用URLConnection发送网络请求,异步
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        
        if (connectionError == nil) {
            NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        }
    }];
}

//GET实例

-(void)methodGet
{
    // 1. 实例化URL
    NSString *urlStr = [NSString stringWithFormat:@"XXXXXXusername=%@&password=%@", userName, userPwd];
    NSURL *url = [NSURL URLWithString:urlStr];
    // 2. 建立URLRequest  默认就是GET请求
    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    //利用URLConnection发送网络请求
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        
        //请求成功
        if (connectionError == nil) {
            NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        }
    }];
}

作者:Darren

微博:@IT_攻城师

github:@Darren90

博客:http://www.cnblogs.com/fengtengfei/

欢迎您的访问...


推荐阅读