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 () ...
随机推荐
- Pig源代码分析: 简析运行计划的生成
摘要 本文通过跟代码的方式,分析从输入一批Pig-latin到输出物理运行计划(与launcher引擎有关,通常是MR运行计划.也能够是Spark RDD的运行算子)的总体流程. 不会详细涉及AST怎 ...
- UVA - 10167 - Birthday Cake (简单枚举)
思路:简单枚举 AC代码: #include <cstdio> #include <cstring> #include <iostream> #include &l ...
- ellipsize-TextView省略号的设定
ellipsize主要是当TextView的文字过长的时候,我们可以让它显示省略号 用法如下: 在xml中 <!--省略号在结尾--> android:ellipsize = " ...
- amazeui的表单开关插件的自定义事件必须添加.bootstrapSwitch 命名空间,给了我们什么启示
amazeui的表单开关插件的自定义事件必须添加.bootstrapSwitch 命名空间,给了我们什么启示 一.总结 一句话总结:详细看使用文档(说明文档说的真的是非常详细呢,不过循序渐进,不同阶段 ...
- Java学习笔记三
1.面向过程思想,强调的是过程(即动作,函数):面向对象思想,强调的是对象. 2.类与对象关系:类是对事物的描述(属性和行为-方法),对象是类的实例.对象通过new生成.属性也称成员变量;方法也称成员 ...
- 相对路径 System.Web HttpServerUtilityBase Server.MapPath("~/")
相对路径 System.Web HttpServerUtilityBase Server.MapPath("~/")
- C# json 总结
json格式字符串转换为实体类,大括号 {} 表示对象,[] 数组表示列表. json文件读取到内存中就是字符串,.NET操作json就是生成与解析json字符串. 添加引用:using Newton ...
- Java中的线程模型及实现方式
概念: 线程是一个程序内部的顺序控制流 线程和进程的比较: 每个进程都有独立的代码和数据空间(进程上下文),进程切换的开销大. 线程:轻量的进程,同一类线程共享代码和数据空间,每个线程有独立的运行栈和 ...
- Bag of Features (BOF)图像检索算法
1.首先.我们用surf算法生成图像库中每幅图的特征点及描写叙述符. 2.再用k-means算法对图像库中的特征点进行训练,生成类心. 3.生成每幅图像的BOF.详细方法为:推断图像的每一个特征点与哪 ...
- [TS] Implement a doubly linked list in TypeScript
In a doubly linked list each node in the list stores the contents of the node and a pointer or refer ...