ios开发网络学习:一:NSURLConnection发送GET,POST请求
#import "ViewController.h" @interface ViewController ()<NSURLConnectionDataDelegate>
/** 注释 */
@property (nonatomic, strong) NSMutableData *resultData;
@end @implementation ViewController #pragma mark ----------------------
#pragma mark lazy loading
-(NSMutableData *)resultData
{
if (_resultData == nil) {
_resultData = [NSMutableData data];
}
return _resultData;
}
#pragma mark ----------------------
#pragma mark Events
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
[self delegate];
} /*
请求:请求头(NSURLRequest默认包含)+请求体(GET没有)
响应:响应头(真实类型--->NSHTTPURLResponse)+响应体(要解析的数据)
*/
#pragma mark ----------------------
#pragma mark Methods
-(void)sync
{
/*
GET:http://120.25.226.186:32812/login?username=123&pwd=456&type=JSON
协议+主机地址+接口名称+?+参数1&参数2&参数3
post:http://120.25.226.186:32812/login
协议+主机地址+接口名称
*/
//GET,没有请求体
//1.确定请求路径
NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=520it&pwd=520it&type=JSON"]; //2.创建请求对象
//请求头不需要设置(默认的请求头)
//请求方法--->默认为GET
NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url]; //3.发送请求
//真实类型:NSHTTPURLResponse
NSHTTPURLResponse *response = nil;
/*
第一个参数:请求对象
第二个参数:响应头信息
第三个参数:错误信息
返回值:响应体
*/
//该方法是阻塞的,即如果该方法没有执行完则后面的代码将得不到执行
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil]; //4.解析 data--->字符串
//NSUTF8StringEncoding
NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]); NSLog(@"%zd",response.statusCode);
} -(void)async
{
//1.确定请求路径
NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=520it&pwd=520it&type=JSON"]; //2.创建请求对象
//请求头不需要设置(默认的请求头)
NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url]; //3.发送异步请求
/*
第一个参数:请求对象
第二个参数:队列 决定代码块completionHandler的调用线程
第三个参数:completionHandler 当请求完成(成功|失败)的时候回调
response:响应头
data:响应体
connectionError:错误信息
*/
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) { //4.解析数据
NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]); NSHTTPURLResponse *res = (NSHTTPURLResponse *)response;
NSLog(@"%zd",res.statusCode);
NSLog(@"%@",[NSThread currentThread]);
}];
} -(void)delegate
{
//1.确定请求路径
NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=123&pwd=123&type=JSON"]; //2.创建请求对象
NSURLRequest *request = [NSURLRequest requestWithURL:url]; //3.设置代理,发送请求
//3.1
//[NSURLConnection connectionWithRequest:request delegate:self]; //3.2
//[[NSURLConnection alloc]initWithRequest:request delegate:self]; //3.3 设置代理,时候发送请求需要检查startImmediately的值
//(startImmediately == YES 会发送 | startImmediately == NO 则需要调用start方法)
NSURLConnection * connect = [[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:NO]; //调用开始方法
[connect start]; // [connect cancel];//取消
} #pragma mark ----------------------
#pragma mark NSURLConnectionDataDelegate
//1.当接收到服务器响应的时候调用
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(@"%s",__func__);
} //2.接收到服务器返回数据的时候调用,调用多次
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSLog(@"%s",__func__); //拼接数据
[self.resultData appendData:data];
}
//3.当请求失败的时候调用
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"%s",__func__);
} //4.请求结束的时候调用
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"%s",__func__); NSLog(@"%@",[[NSString alloc]initWithData:self.resultData encoding:NSUTF8StringEncoding]);
}
@end
二:POST请求
#import "ViewController.h" @interface ViewController () @end @implementation ViewController
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
[self post];
} -(void)post
{
//1.确定请求路径
NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login"]; //2.创建可变请求对象
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; //3.修改请求方法,POST必须大写
request.HTTPMethod = @"POST"; //设置属性,请求超时
request.timeoutInterval = ; //设置请求头User-Agent
//注意:key一定要一致(用于传递数据给后台)
[request setValue:@"ios 10.1" forHTTPHeaderField:@"User-Agent"]; //4.设置请求体信息,字符串--->NSData
request.HTTPBody = [@"username=520it&pwd=123&type=JSON" dataUsingEncoding:NSUTF8StringEncoding]; //5.发送请求
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) { //6.解析数据,NSData --->NSString
NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
}];
} @end
###0 补充(static)
static关键字会在声明变量的时候分配内存,在程序运行期间只分配一次内存。之后再访问时,实际都是在访问原先分配的内存
如果使用static来修饰局部变量,那么局部变量在代码块结束后将不会回收,下次使用保持上次使用后的值。
如果使用static来修饰全局变量,那么表示该全局变量只在本文件中有效,外界无法使用extern来引用。static变量的作用域被限制在定义变量的当前文件中,其它文件是不能访问的。
####1.NSURLConnection使用
- 1.1 NSURLConnection同步请求(GET)
(1)步骤
01 设置请求路径
02 创建请求对象(默认是GET请求,且已经默认包含了请求头)
03 使用NSURLSession sendsync方法发送网络请求
04 接收到服务器的响应后,解析响应体
(2)相关代码
```objc
//1.确定请求路径
NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=520it&pwd=520it&type=XML"];
// NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/video?type=XML"];
//2.创建一个请求对象
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//3.把请求发送给服务器
//sendSynchronousRequest 阻塞式的方法,会卡住线程
NSHTTPURLResponse *response = nil;
NSError *error = nil;
/*
第一个参数:请求对象
第二个参数:响应头信息,当该方法执行完毕之后,该参数被赋值
第三个参数:错误信息,如果请求失败,则error有值
*/
//该方法是阻塞式的,会卡住线程
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
//4.解析服务器返回的数据
NSString *str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
```
- 1.2 NSURLConnection异步请求(GET-SendAsync)
(1)相关说明
01 该方法不会卡住当前线程,网络请求任务是异步执行的
(2)相关代码
```objc
//1.确定请求路径
NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=520it&pwd=520it"];
//2.创建一个请求对象
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//3.把请求发送给服务器,发送一个异步请求
/*
第一个参数:请求对象
第二个参数:回调方法在哪个线程中执行,如果是主队列则block在主线程中执行,非主队列则在子线程中执行
第三个参数:completionHandlerBlock块:接受到响应的时候执行该block中的代码
response:响应头信息
data:响应体
connectionError:错误信息,如果请求失败,那么该参数有值
*/
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse * __nullable response, NSData * __nullable data, NSError * __nullable connectionError) {
//4.解析服务器返回的数据
NSString *str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
//转换并打印响应头信息
NSHTTPURLResponse *r = (NSHTTPURLResponse *)response;
NSLog(@"--%zd---%@--",r.statusCode,r.allHeaderFields);
}];
```
- 1.3 NSURLConnection异步请求(GET-代理)
(1)步骤
01 确定请求路径
02 创建请求对象
03 创建NSURLConnection对象并设置代理
04 遵守NSURLConnectionDataDelegate协议,并实现相应的代理方法
05 在代理方法中监听网络请求的响应
(2)设置代理的几种方法
```objc
/*
设置代理的第一种方式:自动发送网络请求
[[NSURLConnection alloc]initWithRequest:request delegate:self];
*/
/*
设置代理的第二种方式:
第一个参数:请求对象
第二个参数:谁成为NSURLConnetion对象的代理
第三个参数:是否马上发送网络请求,如果该值为YES则立刻发送,如果为NO则不会发送网路请求
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:NO];
//调用该方法控制网络请求的发送
[conn start];
*/
//设置代理的第三种方式:使用类方法设置代理,会自动发送网络请求
NSURLConnection *conn = [NSURLConnection connectionWithRequest:request delegate:self];
//取消网络请求
//[conn cancel];
```
(3)相关的代理方法
```objc
/*
1.当接收到服务器响应的时候调用
第一个参数connection:监听的是哪个NSURLConnection对象
第二个参数response:接收到的服务器返回的响应头信息
*/
- (void)connection:(nonnull NSURLConnection *)connection didReceiveResponse:(nonnull NSURLResponse *)response
/*
2.当接收到数据的时候调用,该方法会被调用多次
第一个参数connection:监听的是哪个NSURLConnection对象
第二个参数data:本次接收到的服务端返回的二进制数据(可能是片段)
*/
- (void)connection:(nonnull NSURLConnection *)connection didReceiveData:(nonnull NSData *)data
/*
3.当服务端返回的数据接收完毕之后会调用
通常在该方法中解析服务器返回的数据
*/
-(void)connectionDidFinishLoading:(nonnull NSURLConnection *)connection
/*4.当请求错误的时候调用(比如请求超时)
第一个参数connection:NSURLConnection对象
第二个参数:网络请求的错误信息,如果请求失败,则error有值
*/
- (void)connection:(nonnull NSURLConnection *)connection didFailWithError:(nonnull NSError *)error
```
(4)其它知识点
```objc
01 关于消息弹窗第三方框架的使用
SVProgressHUD
02 字符串截取相关方法
- (NSRange)rangeOfString:(NSString *)searchString;
- (NSString *)substringWithRange:(NSRange)range;
```
- 1.4 NSURLConnection发送POST请求
(1)发送POST请求步骤
a.确定URL路径
b.创建请求对象(可变对象)
c.修改请求对象的方法为POST,设置请求体(Data)
d.发送一个异步请求
e.补充:设置请求超时,处理错误信息,设置请求头(如获取客户端的版本等等,请求头是可设置可不设置的)
(2)相关代码
```objc
//1.确定请求路径
NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login"];
//2.创建请求对象
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//2.1更改请求方法
request.HTTPMethod = @"POST";
//2.2设置请求体
request.HTTPBody = [@"username=520it&pwd=520it" dataUsingEncoding:NSUTF8StringEncoding];
//2.3请求超时
request.timeoutInterval = 5;
//2.4设置请求头
[request setValue:@"ios 9.0" forHTTPHeaderField:@"User-Agent"];
//3.发送请求
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * __nullable response, NSData * __nullable data, NSError * __nullable connectionError) {
//4.解析服务器返回的数据
if (connectionError) {
NSLog(@"--请求失败-");
}else
{
NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
}
}];
```
- 1.5 URL中文转码问题
```objc
//1.确定请求路径
NSString *urlStr = @"http://120.25.226.186:32812/login2?username=小码哥&pwd=520it";
NSLog(@"%@",urlStr);
//中文转码操作
urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"%@",urlStr);
NSURL *url = [NSURL URLWithString:urlStr];
```
ios开发网络学习:一:NSURLConnection发送GET,POST请求的更多相关文章
- ios开发网络学习三:NSURLConnection小文件大文件下载
一:小文件下载 #import "ViewController.h" @interface ViewController ()<NSURLConnectionDataDele ...
- iOS开发——网络篇——HTTP/NSURLConnection(请求、响应)、http响应状态码大全
一.网络基础 1.基本概念> 为什么要学习网络编程在移动互联网时代,移动应用的特征有几乎所有应用都需要用到网络,比如QQ.微博.网易新闻.优酷.百度地图只有通过网络跟外界进行数据交互.数据更新, ...
- ios开发网络学习四:NSURLConnection大文件断点下载
#import "ViewController.h" @interface ViewController ()<NSURLConnectionDataDelegate> ...
- ios开发网络学习AFN框架的使用一:get和post请求
#import "ViewController.h" #import "AFNetworking.h" @interface ViewController () ...
- ios开发网络学习六:设置队列请求与RunLoop
#import "ViewController.h" @interface ViewController ()<NSURLConnectionDataDelegate> ...
- ios开发网络学习十二:NSURLSession实现文件上传
#import "ViewController.h" // ----WebKitFormBoundaryvMI3CAV0sGUtL8tr #define Kboundary @&q ...
- ios开发网络学习五:输出流以及文件上传
一:输出流 #import "ViewController.h" @interface ViewController ()<NSURLConnectionDataDelega ...
- ios开发网络学习二:URL转码以及字典转模型框架MJExtension的使用
一:url转码,当url中涉及到中文的时候,要考虑转码,用UTF8对中文的url进行转码 #import "ViewController.h" @interface ViewCon ...
- ios开发网络学习AFN三:AFN的序列化
#import "ViewController.h" #import "AFNetworking.h" @interface ViewController () ...
随机推荐
- [AngularFire] Resolve snapshotChanges doesn't emit value when data is empty
Updated to AngularFire2 v5.0. One important change is that you need to call .snapshotChanges() or .v ...
- Qt 5.11的QChar、QString、QTextBoundaryFinder和双向文本算法现在完全兼容Unicode 10
本文翻译自:Qt 5.11 released 原文作者: Qt公司CTO兼Qt开源项目维护官Lars Knoll翻译校审:Richard.Hongfei.Haipeng 5月22日,我们提发布了Qt ...
- C# json 总结
json格式字符串转换为实体类,大括号 {} 表示对象,[] 数组表示列表. json文件读取到内存中就是字符串,.NET操作json就是生成与解析json字符串. 添加引用:using Newton ...
- chocolatey 的安装与安装过程中的注意事项
安装的windows需求 Windows 7+ / Windows Server 2003+ PowerShell v2+ .NET Framework 4+ 注意:chocolatey的网站可能 ...
- 洛谷——P1823 音乐会的等待
https://www.luogu.org/problem/show?pid=1823 题目描述 N个人正在排队进入一个音乐会.人们等得很无聊,于是他们开始转来转去,想在队伍里寻找自己的熟人.队列中任 ...
- 洛谷 P1599 结算日
洛谷 P1599 结算日 题目描述 “不放债不借债”,贝西多么希望自己可以遵循这个忠告.她已经和她的N(1 <= N <= 100,000)个朋友有了债务关系,或者借债了,或者放债了.她的 ...
- 00096_Properties类
1.Properties类介绍 (1)Properties 类表示了一个持久的属性集.Properties 可保存在流中或从流中加载.属性列表中每个键及其对应值都是一个字符串: (2)特点 Hasht ...
- 洛谷——P1179 数字统计
https://www.luogu.org/problem/show?pid=1179 题目描述 请统计某个给定范围[L, R]的所有整数中,数字 2 出现的次数. 比如给定范围[2, 22],数字 ...
- oracle里long类型的总结
转自原文oracle中long类型为什么不推荐使用 不是不推荐使用的,是一般用不到,而有些时候是会用到的,所以不能一概而论.1.LONG 数据类型中存储的是可变长字符串,最大长度限制是2GB.2.对于 ...
- POJ 3264 Balanced Lineup 线段树RMQ
http://poj.org/problem?id=3264 题目大意: 给定N个数,还有Q个询问,求每个询问中给定的区间[a,b]中最大值和最小值之差. 思路: 依旧是线段树水题~ #include ...