NNSURLConnection 发送GET请求

1.苹果原生(自带)

NSURLConnection:用法简单,最古老最经典最直接的一种方案

NSURLSession:功能比NSURLConnection更加强大,苹果目前比较推荐只用这种技术

CFNetwork:NSURL的底层。纯c语言


第三方框架

AFNetworking:

MKNetworkKit



NSURLConnection的使用步骤

1.创建一个NSURL对象,设置请求路径

2.传入NSURL创建的一个NSURLRequest对象,设置请求头和请求体(设置完成后 这时候已经是一个很完整的请求了)

3.利用NSURLConnection发送这个请求给服务器端。


以下是示例代码

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
   
    [self async];
}

-(void)async{
    
    NSURL *url=[NSURL URLWithString:@"http://120.25.226.186:32812/login?username=520it&pwd=520it&type=JSON"];
    
    
    NSURLRequest *requset=[[NSURLRequest alloc]initWithURL:url];
    
    /*
     第一个参数:请求对象
     参数2:队列:决定代码块的调用线程
     参数3:completionHandler 是一个回调模块 当请求完成(成功或者失败)的时候回调
     response:响应头
     data:响应体
     connectionError:错误信息
     */
//    NSURLResponse *response=nil;
    [NSURLConnection sendAsynchronousRequest:requset queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
       //解析数据
        
        NSHTTPURLResponse *sel=(NSURLResponse *)response;
        NSLog(@"-----%@--------%zd",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding],sel.statusCode);
        
        
        
        
    }];
}

-(void)sync
    {
        //1确定请求路径
        NSURL *url=[NSURL URLWithString:@"http://120.25.226.186:32812/login?username=520it&pwd=520it&type=JSON"];
        
        //2.创建请求
        NSURLRequest *request=[NSURLRequest requestWithURL:url];
        //3.发送请求
        NSHTTPURLResponse *response=nil;
        NSData* data=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
        //解析 NSData---------->NSString
        NSLog(@"----%@-----",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
        //
        //

    }

@end


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值