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 () ...
随机推荐
- [C++11] 默认构造函数
类通过一个特殊的构造函数来控制默认初始化过程.这个函数就是默认构造函数.默认构造函数无需不论什么实參. 我们能够显示的定义默认构造函数也能够让编译器为我们生成默认构造函数. 默认构造函数以例如以下规则 ...
- artDialog提示框、对话框
/** * 警告 * @param {String}消息内容 */ artDialog.alert = function (content, callback) { return artDialog( ...
- 用 runcloud.io 免费部署、优化管理你的多个VPS( 目前支持 Ubuntu 16.04 )
使用RunCloud.io轻松实现Web部署 使用VPS.云服务器,通常会安装基本的操作系统,之后必须自己安装Apache,MySQL,PHP,尤其是服务器的性能优化,这对大多数人来说可能是非常具有挑 ...
- 对 hiren bootcd 15.2 中的 XP 系统作了汉化, 同时支持中文输入法。提供下载
对 hiren bootcd 15.2 中的 XP 系统作了汉化, 同时支持中文输入法.提供下载 对该PE 中的 XP 系统作了汉化, 由于一个 中文字库 就要 10M 多:加之原系统过于精简,对中文 ...
- Elasticsearch5.0.1 + Kibana5.0.1 + IK 5.0.1
Elasticsearch5.0.1 + Kibana5.0.1 + IK 5.0.1安装记录 最近工作需要,开始研究ES,当前ES的最新版本为5.0.1,从之前的2.x的版本号一下升级到5.x,主要 ...
- C# json 总结
json格式字符串转换为实体类,大括号 {} 表示对象,[] 数组表示列表. json文件读取到内存中就是字符串,.NET操作json就是生成与解析json字符串. 添加引用:using Newton ...
- Spring学习总结(11)——Spring JMS MessageConverter介绍
消息转换器MessageConverter MessageConverter的作用主要有两方面,一方面它可以把我们的非标准化Message对象转换成我们的目标Message对象,这主要是用在发送消息的 ...
- GraphX 图数据建模和存储
背景 简单分析一下GraphX是怎么为图数据建模和存储的. 入口 能够看GraphLoader的函数. def edgeListFile( sc: SparkContext, path: String ...
- hdu 2795 Billboard(线段树单点更新)
Billboard Time Limit: 20000/8000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Total ...
- jquery中prop()和attr()的使用
jquery1.6+出现的prop()方法. • 对于HTML元素本身就带有的固有属性,在处理时,使用prop方法. • 对于HTML元素我们自己自定义的DOM属性,在处理时,使用attr方法. • ...