HTTP简介:
HTTP(Hypertext transfer protocol),先说下着几个单词,Hypertext是超文本(除了HTML外,也可以是带有超链接的XML或JSON),protocol是协议,transfer翻译应该是移交(也可以翻译成传输,运输,还有一个更具体的词是transport),最开始学校学习Http的所有市面能见到的书籍都翻译成超文本传输协议,Http设计的本身是为了移交和操作资源
Http提供了几种方法访问资源.
Http协议中定义了与服务器之间交互的八个方法:get(获取资源),post(向指定资源提交数据进行处理请求,增加或者更新资源),put(向指定资源位置上传其最新内容 ),delete(请求服务器删除Request-URI所标识的资源);
GET和POST异同点
1.可见性,get访问时URL是所有人都可见的,post则是不可见的.
2.长度限制
get和post传递长度都是是没有限制的
之所以有人说get的长度是有限制的,是因为get是放在URL中一起去请求的,浏览器限制了URL的长度导致GET的参数不能太长,大概长读是1 KB;其实HTTP协议对URL的长度进行限制
POST是请求大小是没有限制的,Web服务器会对post请求进行控制,postIIS请求限制为最多为28.6M,get请求IIS限制为2KB,如有需要可根据需求修改长度大小
3.安全性,与 post相比,get的安全性较差,因为所发送的数据是 URL 的一部分(登录的时候提交数据应该没人会用get),post比get更安全,因为参数不会被保存在浏览器历史或 web 服务器日志中。
4.数据类型,get只允许 ASCII 字符; post传递没有限制,也允许二进制数据。
5 . 编码类型, form的enctype属性为表单控件的内容编码方式,常见有两种: application/x-www-form-urlencoded(默认)和multipart/form-data, 不管get还是post都可以使用者两种编码方式,当表单中含有type=file文件控件的时候发送方式只能使用post,内容编码方式只能使用multipart/part/form-data.
6 . 书签, 缓存 , get请求可以收藏为书签,能被缓存, post不可以被收藏为书签,不可以被缓存
7 . 取值方式 , ASP.NET中对于get请求Request.QueryString取值, 对Post请求使用Request.Form
我们在代码中是如何实现的呢?
#define BASE_URL @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213"
//把上面的数字换成两部分 以 ?为分界线
#define URL_POST1 @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx"
#define URL_POST2 @"date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213"
GET同步 <注意这里使用了MJExtension字典转模型框架>
MJExtension:http://www.jianshu.com/p/bbe7c88d5756
#pragma mark ----------------GET同步--------------
-(IBAction)getTong:(UIButton *)sender{
// 1 创建URL对象
NSURL *url = [NSURL URLWithString:BASE_URL];
// 2 创建请求对象
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
// 2.1 创建请求方式 (默认是get这一步可以不写)
[request setHTTPMethod:@"get"];
// 3 创建响应对象(有时会出错)
NSURLResponse *response= nil;
// 4 创建连接对象(同步)
NSError *error;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
// http://www.jianshu.com/p/bbe7c88d5756
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSNumber *lastUpdateTime = dict[@"lastUpdateTime"];
NSLog(@"lastUpdateTime = %@",lastUpdateTime);
NSArray *Array = dict[@"news"];
self.dataArray = [NewsModel mj_objectArrayWithKeyValuesArray:Array];
for (NewsModel *newsModal in self.dataArray) {
NSLog(@"newsModal.title = %@",newsModal.title);
}
}
POST同步
#pragma mark ---------------POST同步-----------------
- (IBAction)postAction1:(UIButton *)sender {
NSLog(@"Post同步");
//1 创建URL对象
NSURL *url =[NSURL URLWithString:URL_POST1];
//2 创建请求对象
NSMutableURLRequest *resuest =[NSMutableURLRequest requestWithURL:url];
//2.1 创建请求方式
[resuest setHTTPMethod:@"post"];//get可以省略 但是post必须要写
//3 设置请求参数
NSData *tempData = [URL_POST2 dataUsingEncoding:NSUTF8StringEncoding];
[resuest setHTTPBody:tempData];//设置请求主体 外界看不见数据
//4 创建响应对象
NSURLResponse *response = nil;
//5 创建连接对象
NSError *error;
NSData *data = [NSURLConnection sendSynchronousRequest:resuest returningResponse:&response error:&error];
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
NSNumber *lastUpdateTime = dict[@"lastUpdateTime"];
NSLog(@"lastUpdateTime = %@",lastUpdateTime);
NSArray *Array = dict[@"news"];
self.dataArray = [NewsModel mj_objectArrayWithKeyValuesArray:Array];
for (NewsModel *newsModal in self.dataArray) {
NSLog(@"newsModal.title = %@",newsModal.title);
}
}
GET connection异步
#pragma mark ---------------GET connection异步-----------------
-(IBAction)getYibu:(UIButton *)sender{
NSURL *url = [NSURL URLWithString:BASE_URL];
NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestReloadRevalidatingCacheData timeoutInterval:10];
//连接服务器
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
[connection start];
}
//NSURLConnectionDataDelegate代理方法
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;
{
NSLog(@"didReceiveResponse");
_tempData = [NSMutableData data];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;{
NSLog(@"didReceiveData");
[_tempData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection;{
_dataArray = [NSMutableArray arrayWithCapacity:1];
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:_tempData options:NSJSONReadingAllowFragments error:nil];
NSNumber *lastUpdateTime = dict[@"lastUpdateTime"];
NSLog(@"lastUpdateTime = %@",lastUpdateTime);
NSArray *Array = dict[@"news"];
self.dataArray = [NewsModel mj_objectArrayWithKeyValuesArray:Array];
for (NewsModel *newsModal in self.dataArray) {
NSLog(@"newsModal.title = %@",newsModal.title);
}
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
NSLog(@"%@",error);
}
GET Session异步
#pragma mark --------------GET Session异步请求-----------------
- (IBAction)getSession:(UIButton *)sender {
NSURL *url =[NSURL URLWithString:BASE_URL];
//创建session对象
NSURLSession *session =[NSURLSession sharedSession];
__weak typeof(self)temp =self;
//创建task(该方法内部默认使用get)直接进行传递url即可
NSURLSessionDataTask *dataTask =[session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
temp.dataArray = [NSMutableArray arrayWithCapacity:1];
//数据操作
NSDictionary *dict =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSNumber *lastUpdateTime = dict[@"lastUpdateTime"];
NSLog(@"lastUpdateTime = %@",lastUpdateTime);
NSArray *Array = dict[@"news"];
self.dataArray = [NewsModel mj_objectArrayWithKeyValuesArray:Array];
for (NewsModel *newsModal in self.dataArray) {
NSLog(@"newsModal.title = %@",newsModal.title);
}
NSLog(@"idStr = %@",self.dataArray[1].type);
}];
//数据操作
[dataTask resume];
// 注意数据操作之后无法获得数据
for (NewsModel *newsModal in self.dataArray) {
NSLog(@"newsModal.title = %@",newsModal.title);
}
}
POST Session异步请求
#pragma mark -------POST Session异步请求---------
- (IBAction)postSession:(UIButton *)sender {
//创建URL对象
NSURL *url =[NSURL URLWithString:URL_POST1];
//创建请求对象
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"post"];
NSData *tempdata = [URL_POST2 dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:tempdata];
// 3 建立会话 session支持三种类型的任务
// NSURLSessionDataTask //加载数据
// NSURLSessionDownloadTask //下载
// NSURLSessionUploadTask //上传
NSURLSession *session =[NSURLSession sharedSession];
// NSLog(@"%d",[[NSThread currentThread] isMainThread]);
__weak typeof(self)weakSelf = self;
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//解析
_dataArray = [NSMutableArray arrayWithCapacity:1];
NSDictionary *dict =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSNumber *lastUpdateTime = dict[@"lastUpdateTime"];
NSLog(@"lastUpdateTime = %@",lastUpdateTime);
NSArray *Array = dict[@"news"];
self.dataArray = [NewsModel mj_objectArrayWithKeyValuesArray:Array];
for (NewsModel *newsModal in weakSelf.dataArray) {
NSLog(@"newsModal.title = %@",newsModal.title);
}
NSLog(@"当前的线程为%@",[NSThread currentThread]);
//回到主线程 刷新数据 要是刷新就在这里面
dispatch_async(dispatch_get_main_queue(), ^{
for (NewsModel *model in weakSelf.dataArray) {
NSLog(@"summary = %@",model.summary);
}
});
}];
//启动任务
[dataTask resume];
}