NNSURLConnection 发送GET请求

来源:互联网 发布:java调用c语言dll csdn 编辑:程序博客网 时间:2024/05/14 02:23

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


0 0
原创粉丝点击