iOS开发网络学习七:NSURLSession的基本使用get和post请求
#import "ViewController.h" @interface ViewController () @end @implementation ViewController -(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
[self post];
} -(void)get
{
//1.确定URL
NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=520it&pwd=520it&type=JSON"]; //2.创建请求对象
NSURLRequest *request =[NSURLRequest requestWithURL:url]; //3.创建会话对象
NSURLSession *session = [NSURLSession sharedSession]; //4.创建Task
/*
第一个参数:请求对象
第二个参数:completionHandler 当请求完成之后调用
data:响应体信息
response:响应头信息
error:错误信息当请求失败的时候 error有值
*/
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { //6.解析数据
NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
}]; //5.执行Task
[dataTask resume];
} -(void)get2
{
//1.确定URL
NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=520it&pwd=520it&type=JSON"]; //2.创建请求对象
//NSURLRequest *request =[NSURLRequest requestWithURL:url]; //3.创建会话对象
NSURLSession *session = [NSURLSession sharedSession]; //4.创建Task
/*
第一个参数:请求路径
第二个参数:completionHandler 当请求完成之后调用
data:响应体信息
response:响应头信息
error:错误信息当请求失败的时候 error有值
注意:dataTaskWithURL 内部会自动的将请求路径作为参数创建一个请求对象(GET)
*/
NSURLSessionDataTask *dataTask = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { //6.解析数据
NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
}]; //5.执行Task
[dataTask resume];
} -(void)post
{
//1.确定URL
NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login"]; //2.创建请求对象
NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:url]; //2.1 设置请求方法为post
request.HTTPMethod = @"POST"; //2.2 设置请求体
request.HTTPBody = [@"username=520it&pwd=520it&type=JSON" dataUsingEncoding:NSUTF8StringEncoding]; //3.创建会话对象
NSURLSession *session = [NSURLSession sharedSession]; //4.创建Task
/*
第一个参数:请求对象
第二个参数:completionHandler 当请求完成之后调用 !!! 在子线程中调用
data:响应体信息
response:响应头信息
error:错误信息当请求失败的时候 error有值
*/
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { NSLog(@"%@",[NSThread currentThread]);
//6.解析数据
NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
}]; //5.执行Task
[dataTask resume];
} @end
#####2 NSURLSession的基本使用
(1)使用步骤
使用NSURLSession创建task,然后执行task
(2)关于task
a.NSURLSessionTask是一个抽象类,本身不能使用,只能使用它的子类
b.NSURLSessionDataTask\NSURLSessionUploadTask\NSURLSessionDownloadTask
(3)发送get请求
```objc
//1.创建NSURLSession对象(可以获取单例对象)
NSURLSession *session = [NSURLSession sharedSession];
//2.根据NSURLSession对象创建一个Task
NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=ss&pwd=ss&type=JSON"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//方法参数说明
/*
注意:该block是在子线程中调用的,如果拿到数据之后要做一些UI刷新操作,那么需要回到主线程刷新
第一个参数:需要发送的请求对象
block:当请求结束拿到服务器响应的数据时调用block
block-NSData:该请求的响应体
block-NSURLResponse:存放本次请求的响应信息,响应头,真实类型为NSHTTPURLResponse
block-NSErroe:请求错误信息
*/
NSURLSessionDataTask * dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * __nullable data, NSURLResponse * __nullable response, NSError * __nullable error) {
//拿到响应头信息
NSHTTPURLResponse *res = (NSHTTPURLResponse *)response;
//4.解析拿到的响应数据
NSLog(@"%@\n%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding],res.allHeaderFields);
}];
//3.执行Task
//注意:刚创建出来的task默认是挂起状态的,需要调用该方法来启动任务(执行任务)
[dataTask resume];
```
(4)发送get请求的第二种方式
```objc
//注意:该方法内部默认会把URL对象包装成一个NSURLRequest对象(默认是GET请求)
//方法参数说明
/*
//第一个参数:发送请求的URL地址
//block:当请求结束拿到服务器响应的数据时调用block
//block-NSData:该请求的响应体
//block-NSURLResponse:存放本次请求的响应信息,响应头,真实类型为NSHTTPURLResponse
//block-NSErroe:请求错误信息
*/
- (nullable NSURLSessionDataTask *)dataTaskWithURL:(NSURL *)url completionHandler:(void (^)(NSData * __nullable data, NSURLResponse * __nullable response, NSError * __nullable error))completionHandler;
```
(5)发送POST请求
```objc
//1.创建NSURLSession对象(可以获取单例对象)
NSURLSession *session = [NSURLSession sharedSession];
//2.根据NSURLSession对象创建一个Task
NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login"];
//创建一个请求对象,并这是请求方法为POST,把参数放在请求体中传递
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";
request.HTTPBody = [@"username=520it&pwd=520it&type=JSON" dataUsingEncoding:NSUTF8StringEncoding];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * __nullable data, NSURLResponse * __nullable response, NSError * __nullable error) {
//拿到响应头信息
NSHTTPURLResponse *res = (NSHTTPURLResponse *)response;
//解析拿到的响应数据
NSLog(@"%@\n%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding],res.allHeaderFields);
}];
//3.执行Task
//注意:刚创建出来的task默认是挂起状态的,需要调用该方法来启动任务(执行任务)
[dataTask resume];
```
---
iOS开发网络学习七:NSURLSession的基本使用get和post请求的更多相关文章
- ios开发网络学习:一:NSURLConnection发送GET,POST请求
#import "ViewController.h" @interface ViewController ()<NSURLConnectionDataDelegate> ...
- ios开发网络学习AFN框架的使用一:get和post请求
#import "ViewController.h" #import "AFNetworking.h" @interface ViewController () ...
- ios开发网络学习十二:NSURLSession实现文件上传
#import "ViewController.h" // ----WebKitFormBoundaryvMI3CAV0sGUtL8tr #define Kboundary @&q ...
- ios开发网络学习十一:NSURLSessionDataTask离线断点下载(断点续传)
#import "ViewController.h" #define FileName @"121212.mp4" @interface ViewControl ...
- ios开发网络学习九:NSURLSessionDownloadTask实现大文件下载
一:NSURLSessionDownloadTask:实现文件下载:无法监听进度 #import "ViewController.h" @interface ViewControl ...
- iOS开发——网络Swift篇&NSURLSession加载数据、下载、上传文件
NSURLSession加载数据.下载.上传文件 NSURLSession类支持三种类型的任务:加载数据.下载和上传.下面通过样例分别进行介绍. 1,使用Data Task加载数据 使用全局的 ...
- ios开发网络学习AFN三:AFN的序列化
#import "ViewController.h" #import "AFNetworking.h" @interface ViewController () ...
- ios开发网络学习十:利用文件句柄实现大文件下载
#import "ViewController.h" @interface ViewController ()<NSURLSessionDataDelegate> @p ...
- ios开发网络学习六:设置队列请求与RunLoop
#import "ViewController.h" @interface ViewController ()<NSURLConnectionDataDelegate> ...
随机推荐
- jQuery post 打开新窗口
//使用POST方式打开界面 function doOpenPostWin(url, args, name, windowParam) { //创建表单对象 var _form = $("& ...
- tooltip两个特殊的属性
<body style="margin: 50px;"> <!--两个特殊的属性--> <div id="selection"&g ...
- java 矩阵求逆
package com.yang.matrix; public class TestMatrix { public static void main(String[] args) { // 测试数据 ...
- Atcoder At Beginner Contest 068 D - Decrease (Contestant ver.)
D - Decrease (Contestant ver.) Time limit : 2sec / Memory limit : 256MB Score : 600 points Problem S ...
- JavaScript学习总结(1)——JavaScript基础
一.JavaScript语言特点 1.1.JavaScript是基于对象和事件驱动的(动态的) 它可以直接对用户或客户输入做出响应,无须经过Web服务程序.它对用户的响应,是采用以事件驱动的方式进行的 ...
- jsp 用shiro 的判断 是否有菜单查看的权限
实例:spring-shiro.xml 123 /admin/repairType/index = roles["ROLE_ADMIN"]/admin/user=roles[&qu ...
- POJ——T 1006 Biorhythms
http://poj.org/problem?id=1006 Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 138219 ...
- C++ Traits 技术
Tarits.特性的复数. c++萃取技术就是指它. 实现方式是模板特化. STL中涉及到iterator的地方常常能用到它. gcc的STL与VS的STL略有区别. vs中下列代码,把鼠标放在ite ...
- LocationOnScreen-控件在手机屏幕中的位置坐标
我们可以通过如下的方法获得某个控件在屏幕中的绝对坐标 代码如下: private int[] mHistoryDisplayButtonLocation; private int mHistoryDi ...
- 6 Spring Boot 静态资源处理
转自:https://blog.csdn.net/catoop/article/details/50501706