//

//  ViewController.m

//  UI-NO.18

//

//  Created by Bruce on 15/8/11.

//  Copyright (c) 2015年 Bruce. All rights reserved.

//

/*

 

 http协议:

 超文本传输协议(HTTP,HyperText Transfer Protocol)是互联网上应用最为广泛的一种网络协议。所有的WWW文件都必须遵守这个标准。

http是用于www(万维网)浏览传输数据的一个协议

访问的是远程的网络资源,格式是http://

 

 http://服务器地址 资源的位置

//  http://www.baidu.com/user/chginfo

 

 

 

 

 WWW是环球信息网的缩写,(亦作“Web”、“WWW”、“'W3'”,英文全称为“World Wide Web”),中文名字为“万维网”,"环球网"等,常简称为Web。 分为Web客户端和Web服务器程序。 WWW可以让Web客户端(常用浏览器)访问浏览Web服务器上的页面。 是一个由许多互相链接的超文本组成的系统,通过互联网访问。在这个系统中,每个有用的事物,称为一样“资源”;并且由一个全局“统一资源标识符”(URL)标识;这些资源通过超文本传输协议(Hypertext Transfer Protocol)传送给用户,而后者通过点击链接来获得资源。

 万维网联盟(英语:World Wide Web Consortium,简称W3C),又称W3C理事会。1994年10月在麻省理工学院(MIT)计算机科学实验室成立。万维网联盟的创建者是万维网的发明者蒂姆·伯纳斯-李。

 

 IP协议对应于网络层,TCP协议对应于传输层,而HTTP协议对应于应用层(识别数据内容),

 

 

 http协议的作用:

 (1)规定客户端和服务器之间的数据传输格式

 

 (2)让客户端和服务器能有效地进行数据沟通

 

 

 为什么选择使用HTTP

 

 (1)简单快速  因为HTTP协议简单,所以HTTP服务器的程序规模小,因而通信速度很快

 

 (2)灵活  HTTP允许传输任意类型的数据

 

 (3)HTTP 是非持续连接  限制每次连接只处理一个请求,服务器对客户端的请求做出响应后,马上断开连接,这种方式可以节省传输时间

 

 

 HTTP的通信过程

 (1)请求:客户端向服务器索要数据

 

 (2)响应:服务器返回客户端相应的数据

 

 

 

 

 *****

 HTTP的请求方法:get post

 

 

 

 get:会把请求的内容  拼接到  链接 地址 里面(数据请求的时候  默认是get)

 

 www.baidu.com/user/login?username=刘水,psw=123

 

 get特征:

 1、浏览器和服务器对URL长度有限制,因此在URL后面附带的参数是有限制的,通常不能超过1KB

 2、会把请求的数据 暴露在接口里面

 

 

 post 参数全部放在请求体中  

 这样就保证了 数据的安全

 没有具体的长度限制(唯一的限制 就是 服务器的承受能力)

 

 

 选择GET和POST的建议

 

 (1)如果要传递大量数据,比如文件上传,只能用POST请求

 

 (2)GET的安全性比POST要差些,如果包含机密\敏感信息,建议用POST

 

 (3)如果仅仅是索取数据(数据查询),建议使用GET

 

 (4)如果是增加、修改、删除数据,建议使用POST

 

 

 

 

 

 

 

 

 URL:Uniform Resource Locator(统一资源定位符)

 通过1个URL,能找到互联网上唯一的1个资源

 

 

 

 //    字符串读取网络数据

 NSURL *url = [NSURL URLWithString:@"http://baike.baidu.com/link?url=vis7S5gBFGNFsbWKyvohMqFDMirD45BqSe23YRkb4481UWxZBMHeIEIpQ3XvZLGlWT11XIzxr4_T7R7dEH7GcK"];

 NSString *recvieString = [[NSString alloc]initWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];

 NSLog(@"%@",recvieString);

 */

 

/*

 //    读取网络图片

 NSURL *url = [NSURL URLWithString:@"http://img.baidu.com/img/baike/logo-baike.png"];

 NSData *imageData = [[NSData alloc]initWithContentsOfURL:url];

 NSLog(@"%@",imageData);

 imageView.image = [UIImage imageWithData:imageData];

 */

 

//    同步请求

//    加载完网络数据  才会执行其他操作

//    会暂时 暂停用户响应  不可以操作手机  当网络请求结束后 恢复响应

 

//  异步加载  不会阻塞主线程  不会暂停用户响应 看界面 下载网络数据  是不互相影响的

 

 

//    同步请求

//    请求类 NSURLRequest

//    连接类 NSURLConnection

 

//    同步请求步骤:

//    1、有链接地址(URL)

//    2、创建请求(NSURLRequest)

//    3、连接请求地址 发送请求 返回数据(NSURLConnection)

/*

 //    1、有链接地址(URL)

 NSURL *url = [NSURL URLWithString:@"http://img.baidu.com/img/baike/logo-baike.png"];

 //    2、创建请求(NSURLRequest)

 NSURLRequest *request = [NSURLRequest requestWithURL:url];

 //    3、连接请求地址 发送请求 返回数据

 NSData *recvieData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

 UIImage *image = [UIImage imageWithData:recvieData];

 imageView.frame = CGRectMake(100, 100, image.size.width, image.size.height);

 imageView.image = image;

 */

 

/*

 //    异步请求

 //    1、创建URL地址

 //    2、创建请求

 //    3、连接地址发送异步请求

 

 NSURL *url = [NSURL URLWithString:@"http://m.weather.com.cn/data/101010100.html"];

 NSURLRequest *request = [NSURLRequest requestWithURL:url];

 //    发送异步请求

 [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

 //        connectionError 错误信息

 if (!connectionError) {

 //            response 服务器回应的信息

 NSLog(@"response%@",response);

 //            data 服务器返回的数据内容

 NSLog(@"data:%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);

 }

 

 }];

 

 

 

//    get方式请求数据的步骤

//    1、拼接url的链接地址字符串(把需要发送的内容 拼接到链接地址里面)

//    2、初始化URL

//    3、创建一个请求(可变的请求,需要设置请求的方式)

//    4、发送请求 返回请求内容

 

 

//    需要发送的请求内容

NSString *sendMessage = @"101010100";

//    拼接请求地址

NSString *urlString = [NSString stringWithFormat:@"http://m.weather.com.cn/data/%@.html",sendMessage];

//    初始化URL

NSURL *url = [NSURL URLWithString:urlString];

//    创建请求 设置请求方式

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5];

//    设置请求的方式种类

request.HTTPMethod = @"GET";

__block NSDictionary *recDic = [NSDictionary dictionary];

//    发送请求

NSOperationQueue *queue = [[NSOperationQueue alloc]init];

[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

    

    //        NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);

    

    //        解析JASN数据

    recDic =  [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];

    

    //        NSLog(@"%@",recDic);

    

    //    解决 block里面参数不能外传的问题(不是block的问题  而是异步加载 在不同线程的问题  子线程还未执行完 就已经执行主线程的方法  这时候数据就是空的)

    //        等待子线程里面的任务执行完 在主线程里执行这个方法

    [self performSelectorOnMainThread:@selector(didRecvieData:) withObject:recDic waitUntilDone:YES];

}];

 

 

 

 

 

 

//    POST 请求步骤

//    1、准备POST的数据

//    2、初始化URL

//    3、创建请求   设置请求 (设置请求的方式POST 以及 POST的BODY)

//    4、发送请求 返回数据

 

 //    1、准备POST的数据

 NSString *bodyString = @"PlatformType=3&serviceId=39&brandId=11";

 //    2、初始化URL

 NSURL *url = [NSURL URLWithString:@"http://www.weihuok.com/customer2/GetFault"];

 //    3、创建请求   设置请求 (设置请求的方式POST 以及 POST的BODY)

 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5];

 request.HTTPMethod = @"POST";

 //    HTTPBody 是nsdata类型   需要把  post的数据转成对应格式

 request.HTTPBody = [bodyString dataUsingEncoding:NSUTF8StringEncoding];

 

 //    4、发送请求  返回请求数据

 [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

 NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);

 }];

 

 

 */

#import "ViewController.h"

 

@interface ViewController ()

 

@end

 

@implementation ViewController

 

- (void)viewDidLoad {

    [super viewDidLoad];

    self.view.backgroundColor = [UIColor blackColor];

 

    

    

    [self loadData6];

}

 

//直接读取网页中的字符串

- (void)loadData1

{

    NSURL *url = [NSURL URLWithString:@"https://www.baidu.com"];

    

    NSString *content = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];

    NSLog(@"%@",content);

}

 

//直接读取 网络图片

- (void)loadData2

{

    

    NSURL *url = [NSURL URLWithString:@"http://preview.quanjing.com/is_rm001/is0997q92.jpg"];

    

    NSData *imageData = [NSData dataWithContentsOfURL:url];

    

    UIImageView *imageView = [[UIImageView alloc]initWithFrame:self.view.frame];

    imageView.image = [UIImage imageWithData:imageData];

    imageView.contentMode = UIViewContentModeScaleAspectFit;

    [self.view addSubview:imageView];

}

 

//同步请求

- (void)loadData3

{

    NSURL *url = [NSURL URLWithString:@"http://img.baidu.com/img/baike/logo-baike.png"];

    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    NSError *error;

    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];

    NSLog(@"error:%@",error);

    UIImageView *imageView = [[UIImageView alloc]initWithFrame:self.view.frame];

    imageView.image = [UIImage imageWithData:data];

    imageView.contentMode = UIViewContentModeScaleAspectFit;

    [self.view addSubview:imageView];

}

 

//异步请求

- (void)loadData4

{

    UIImageView *imageView = [[UIImageView alloc]initWithFrame:self.view.frame];

    imageView.contentMode = UIViewContentModeScaleAspectFit;

    [self.view addSubview:imageView];

    

    NSURL *url = [NSURL URLWithString:@"http://img.baidu.com/img/baike/logo-baike.png"];

    NSURLRequest *request = [NSURLRequest requestWithURL:url];

 

 

    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

        imageView.image = [UIImage imageWithData:data];

    }];

    

}

 

//get

- (void)loadData5

{

    NSString *string = @"http://apis.baidu.com/showapi_open_bus/mobile/find?num=13370116152";

    NSURL *url = [NSURL URLWithString:[string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

    NSString *apiKey = @"e7f5ac9e7c42a6c8cb125ee1d7e8779e";

    NSLog(@"%@",url);

    NSMutableURLRequest *requst = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];

    

    [requst addValue:apiKey forHTTPHeaderField:@"apikey"];

    requst.HTTPMethod = @"GET";

    

    [NSURLConnection sendAsynchronousRequest:requst queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

      

        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];

        NSLog(@"==%@",dic);

    }];

    

}

 

- (void)loadData6

{

    //    1、准备POST的数据

 

 

    NSString *string = @"http://www.weihuok.com/customer2/GetService";

    //    2、初始化URL

    NSURL *url = [NSURL URLWithString:[string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

    //    3、创建请求   设置请求 (设置请求的方式POST 以及 POST的BODY)

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5];

 

    request.HTTPMethod = @"POST";

    //    HTTPBody 是nsdata类型   需要把  post的数据转成对应格式

    request.HTTPBody = [[NSString stringWithFormat:@"%@",@{@"PlatformType":@"3"}] dataUsingEncoding:NSUTF8StringEncoding];

    

    //    4、发送请求  返回请求数据

    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

        NSLog(@"=%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);

        

        NSDictionary *content = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];

        

        NSLog(@"%@",content);

    }];

 

}

- (void)loadData

{

    NSString *apiKey = @"  e7f5ac9e7c42a6c8cb125ee1d7e8779e";

    NSNumber *idNum = @(-1);

    

    NSURL *URL = [NSURL URLWithString:[NSString stringWithFormat:@"http://apis.baidu.com/myml/c1c/c1c?%@",idNum]];

    

//    同步请求

    

//    创建请求

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];

    [request addValue:apiKey forHTTPHeaderField:@"apikey"];

    

//    连接服务器数据

    NSData *respondData =  [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

    

//    把NSData 转成 字符串类型

    NSString *respondString = [[NSString alloc]initWithData:respondData encoding:NSUTF8StringEncoding];

    

    NSLog(@"%@",respondString);

}

 

- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

 

@end

 

转载于:https://www.cnblogs.com/wukun16/p/4884146.html

HTTP协议(异步和同步)相关推荐

  1. [ JS 进阶 ] Ajax 详解 (2) :XHR 实例 GET 和 POST 异步和同步

    上一篇文章 我们大概知道了XHR对象是什么东东,也都了解了它的一些属性和方法,那么现在具体来实现一下Ajax技术 和 了解下XHR2对象. 1.实现Ajax 先来创建个XHR对象的实例: var xh ...

  2. Java 异步与同步的区别

    同步: 所有操作完成之后,才会通知用户操作完成了. 异步:不用等所有操作完成之后,就会通知用户操作完成了,然后后台会继续操作直到完成结束. 为了方便理解 举例个常见的 android 网络请求使用的异 ...

  3. 那些年让你迷惑的阻塞、非阻塞、异步、同步

    点击上方"方志朋",选择"置顶或者星标" 你的关注意义重大! 在IT圈混饭吃,不管你用什么编程语言.从事前端还是后端,阻塞.非阻塞.异步.同步这些概念,都需要清 ...

  4. Node.js模拟发起http请求从异步转同步的5种方法

    使用Node.js模拟发起http请求很常用的,但是由于Node模块(原生和第三方库)提供里面的方法都是异步,对于很多场景下应用很麻烦,不如同步来的方便.下面总结了几个常见的库API从异步转同步的几种 ...

  5. java 总结几种线程异步转同步的方法

    转载自https://blog.csdn.net/Veson__/article/details/53898890 在做一款app的时候,用到了一个异步执行的api,而我想要的是同步执行,查了一些资料 ...

  6. 路由器的异步和同步串行接口

    本文以Cisco路由器为例,介绍了路由器上常用接口的类型.特点和应用场合. 1  EIA/TIA 232 EIA/TIA 232有时又被称作RS-232 C.RS(Recommended Standa ...

  7. object转class_从零并发框架(三)异步转同步注解+字节码增强代理实现

    序言 上一节我们学习了异步查询转同步的 7 种实现方式,今天我们就来学习一下,如何对其进行封装,使其成为一个更加便于使用的工具. 思维导图如下: 异步转同步字节码增强 拓展阅读 java 手写并发框架 ...

  8. 多线程是并行还是并发_并发,并行,线程,进程,异步和同步有相关性吗?

    本文翻译自:https://medium.com/swift-india/concurrency-parallelism-threads-processes-async-and-sync-relate ...

  9. ajax中异步属性,ajax中的async属性值之同步和异步及同步和异步区别

    jquery中ajax方法有个属性async用于控制同步和异步,默认是true,即ajax请求默认是异步请求,有时项目中会用到AJAX同步.这个同步的意思是当JS代码加载到当前AJAX的时候会把页面里 ...

  10. (47)FPGA同步复位与异步复位(异步复位同步释放)

    (47)FPGA同步复位与异步复位(异步复位同步释放) 1 文章目录 1)文章目录 2)FPGA入门与提升课程介绍 3)FPGA简介 4)FPGA同步复位与异步复位(异步复位同步释放) 5)技术交流 ...

最新文章

  1. mysql 事务涉及锁吗_MySQL-锁机制和事务
  2. NOIP提高组复赛 知识点整理
  3. 通过影响函数理解黑箱预测
  4. 深入理解计算机系统——bomblab
  5. php mysql bool_关于mysql api中my_bool的取值范围的问题
  6. Redmi K40 Pro将首批搭载骁龙888:或刷新骁龙888最低售价
  7. 从苹果 M1 到英伟达 Grace,“缝合风”为何在芯片大厂中盛行?
  8. 想通过C++寻找后端开发工作如何提升自己?
  9. RabbitMQ~一些术语和最消息的生产
  10. 论文阅读-多任务(2021)-YOLOP:用于自动驾驶目标检测与语义分割的实时多任务模型
  11. 阿里2018校招编程题
  12. vue中怎么点击修改文字_怎么拍照识别文字?什么软件可以识别照片中文字?
  13. 如何修改wifi密码(wifi密码怎么修改在手机上怎么修改)
  14. java1.5_Java15下载 JDK15(Java SE Development Kit 15) 15.0.2 官方正式版 Win64位 下载-脚本之家...
  15. 从程序员到合格的软件设计师
  16. 关于电子计算机的热点,电脑如何变热点?8款电脑wifi热点软件推荐
  17. fifo的rdata_同步Fifo和异步fifo
  18. 驱动启动时遇到:打开服务失败(错误码=6):句柄无效 解决方案
  19. 删库跑路大全 删库跑路
  20. C++、C#、Java、Python、可以获取L2行情实时数据吗?

热门文章

  1. 分区助手找不到盘_C盘的概述与分区
  2. github pages markdown_赏金$25000的GitHub漏洞:通过 GitHub Pages 不安全的Kramdown配置实现多个RCE...
  3. typescript的基本结构_上帝视角看 TypeScript
  4. Python-Matplotlib可视化(4)——添加注释让统计图通俗易懂
  5. Ubuntu18.04系统中python3.7安装MultiNEAT库
  6. Telnet命令在Linux / Unix中的用法
  7. numpy矩阵乘法_NumPy矩阵乘法
  8. 在Selenium Chrome驱动程序上运行测试
  9. 开课吧课堂:C++开发语言的应用方向有哪些?
  10. oracle11g-R2静默安装报错[INS-32013]解决方案