HTTP协议(异步和同步)

//

//  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