网络请求

网络请求

http和https

URL

  • URL的基本格式 = 协议://主机地址/路径
  • 协议:不同的协议代表不同的资源查找方式和资源的传输方式
  • 主机地址:存放资源的主机的IP地址(域名)
  • 路径:资源在主机中的位置

C/S模式

  • client和server在相距很远的计算机上
  • client是将用户的要求提交给server,再将server返回的结果展示给用户
  • server是将接受用户程序提出的服务请求,进行相应的处理,再讲结果返还给用户

HTTPS

  • 安全超文本传输协议,在HTTP基础上使用SSL进行信息交换
  • SSL:是运行在TCP和IP层之上,应用层之下的,为应用程序提供加密数据通道
  • https协议需要到CA申请证书,一般需要收费
  • http和https使用完全不同的连接方式,所以端口也不一样,前者80,后者443
  • http的链接简单,是无状态的,传输完一次数据就立刻断开

get和post

  • get是通过网址字符串传输数据,post是通过data
  • get允许网址字符串最多255字节,post使用NSdata,容量超过1G(实际允许不超过4G)
  • get的所有传输给服务的数据,都会显示在网址里,直接可见的,而post的数据被转成NSData,无法直接读取,所以较为安全

实现网络编程

  • 若网址字符串URLString中有汉字,需要用一下方式转码
str  = [str stringByAddingPercentEscapesUsingEncoding:[ NSCharacterSet URLQueryAllowedCharacterSet]];

NSURLConnection(ios9之后已经弃用了)

get请求

  • 发送同步的get请求并解析数据
//定义的宏,一种是get用到的url,一种是post用到的url
#define KURL @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20151101&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213"
#define PURL @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx"
    //发送同步的get请求
    NSURL *url  =[NSURL URLWithString:KURL];
    //    NSLog(@"%@,%@",url.scheme,url.host);
    //    1.url 2.httpcache的方式 3.超时时间
    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
    //    发送请求
    NSURLResponse *response = nil;
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
    if (data) {
        id json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"%@",json);
        //response是响应(包含响应头和响应体)
        NSLog(@"%@",response);
    }
  • 发送异步的get请求(block方式)并解析数据
//异步get
    NSURL *url = [NSURL URLWithString:KURL];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    //    1.request 2. 主队列 3. 返回结果的block
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        id json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"%@",json);
    }];
    NSLog(@"先走这里");
  • 发送异步的get请求(代理方式)并解析数据
   //代理异步get(事先引入代理NSURLConnectionDataDelegate)
- (void)delegateGet
{
    NSURL *url = [NSURL URLWithString:KURL];
    //    创建请求
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    //    连接
    NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
    //    开始请求
    [connection start];
    //
    //    [connection cancel]; //取消
}
    //服务器接收到请求,开始响应,准备返回数据
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{

}
//接收数据(如果data比较大,会走很多次,需要拼接)
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    //    把请求到的数据data拼接
    [self.data appendData:data];
}
//请求数据结束
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    id json = [NSJSONSerialization JSONObjectWithData:self.data options:NSJSONReadingAllowFragments error:nil];
    NSLog(@"%@",json);
}
//失败
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{

}

post

  • 发送异步的post请求(block)并解析数据
#pragma mark 异步post
//异步post
- (void)post
{
    //POST
    NSURL *url = [NSURL URLWithString:PURL];
    NSMutableURLRequest *requset = [NSMutableURLRequest requestWithURL:url];
    //    设置请求方式(post请求方式和参数必须设置)
    requset.HTTPMethod =@"POST";
    //    设置请求参数
    NSString *str =@"date=20151101&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213";
    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
    requset.HTTPBody = data;
    //    设置请求头
    //    requset setValue:<#(nullable NSString *)#> forHTTPHeaderField:<#(nonnull NSString *)#>
    [NSURLConnection sendAsynchronousRequest:requset queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        id json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"%@",json);
    }];
}
  • 发送异步的post请求(代理)并解析数据
//代理异步post(代理方法与get是一样的,并且实现原理是相同的)
- (void)delegatePost
{
    NSURL *url = [NSURL URLWithString:PURL];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";
    NSString *str = @"date=20151101&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213";
    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
    request.HTTPBody = data;
    NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
    [connection start];
}

NSURLSession

get

  • 发送异步的get请求(block)并解析数据
- (void)blockGet
{
    //sessionGet
    //初始化session
    NSURLSession *session = [NSURLSession sharedSession];
    //    get请求
    NSURLSessionDataTask *task =[session dataTaskWithURL:[NSURL URLWithString:@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20151101&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213"] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        id json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"%@",json);
    }];
    //开启任务(默认挂起,需要手动开启)
    [task resume];
}
  • 发送异步的get请求(代理)并解析数据
- (void)delegateGet
{
    //    控制任务的相关属性(事先引入代理NSURLSessionDataDelegate)
    NSURLSessionConfiguration *configuration =  [NSURLSessionConfiguration defaultSessionConfiguration];
    //初始化session
    //1.任务的控制面板 2.代理 3.代理回调的线程(一般是主线程)
    NSURLSession *session  = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    NSURLSessionDataTask *dataTask = [session dataTaskWithURL:[NSURL URLWithString:@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20151101&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213"]];
    [dataTask resume];
}
//接收请求头
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(nonnull NSURLResponse *)response completionHandler:(nonnull void (^)(NSURLSessionResponseDisposition))completionHandler
{
    //允许处理服务器的响应,才会继续接受服务器返回的数据
    completionHandler(NSURLSessionResponseAllow);
}
//接收数据
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
    [self.data appendData:data];
}
//结束接收数据或者出错
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
    if (!error) {
        id json  = [NSJSONSerialization JSONObjectWithData:self.data options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"%@",json);
    }
}
  • 发送异步的post请求(block)并解析数据
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx"]];
    //设置请求方法
    request.HTTPMethod = @"POST";
    request.HTTPBody = [@"date=20151101&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213" dataUsingEncoding:NSUTF8StringEncoding];
    //初始化
    NSURLSession  *session = [NSURLSession sharedSession];
    //创建任务
    NSURLSessionDataTask *datatask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        //解析数据
        id json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"%@",json);
    }];
//    开启
    [datatask resume];
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,496评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,407评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,632评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,180评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,198评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,165评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,052评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,910评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,324评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,542评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,711评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,424评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,017评论 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,668评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,823评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,722评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,611评论 2 353

推荐阅读更多精彩内容

  • AFHTTPRequestOperationManager 网络传输协议UDP、TCP、Http、Socket、X...
    Carden阅读 4,337评论 0 12
  • 同步请求可以从因特网请求数据, 一旦发送同步请求,程序将停止用户交互,直至服务器返回数据完成, 才可以进行下一步操...
    小灬博阅读 877评论 2 4
  • URL URL 全称是Uniform Resource Locator,即统一资源定位符,通过一个URL,可以找到...
    fwlong阅读 2,091评论 0 4
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,651评论 18 139
  • http和https URL全称是Uniform Resource Locator(统一资源定位符)通过1个URL...
    云之君兮鹏阅读 1,355评论 7 15