您的位置:首页 > 移动开发 > IOS开发

ios开发网络学习:一:NSURLConnection发送GET,POST请求

2016-09-10 22:25 363 查看
#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 = 10;

//设置请求头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];

```
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: