苹果原生发送HTTP请求

2017-02-15  本文已影响141人  Z了个L
// NSURLSession的基本使用(发送GET和POST请求)
// ViewController.h
#import <UIKit/UIKit.h>

@interface ViewController : UIViewController


@end

// ViewController.m
#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController
#pragma mark --------------------
#pragma mark Events
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self get1];
//    [self get2];
//    [self post];
}

#pragma mark --------------------
#pragma mark Methods
-(void)get1
{
    //1.确定URL
    NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=xiaozhang&pwd=123456&type=JSON"];

    //2.创建可变的请求对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

    //3.获得会话对象
    NSURLSession *session = [NSURLSession sharedSession];

    //4.根据会话对象创建Task
    /*
     第一个参数:请求对象
     第二个参数:completionHandler 请求结束的时候调用
        data:响应体信息
        response:响应头信息
        error:错误信息
     completionHandler:该block块在子线程中调用
     */
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

        //6.解析数据
        NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
        NSLog(@"%@",[NSThread currentThread]);
    }];

    //5.执行task
    [dataTask resume];
}

-(void)get2
{
    //1.确定URL
    NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=xiaozhang&pwd=123456&type=JSON"];

    //2.创建可变的请求对象
    //NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

    //3.获得会话对象
    NSURLSession *session = [NSURLSession sharedSession];

    //4.根据会话对象创建Task
    /*
     第一个参数:url
     第二个参数:completionHandler 请求结束的时候调用
     data:响应体信息
     response:响应头信息
     error:错误信息
     completionHandler:该block块在子线程中调用
     */
    //该方法内部会自动把url包装成一个请求对象--GET
    NSURLSessionDataTask *dataTask = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

        //6.解析数据
        NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
        NSLog(@"%@",[NSThread currentThread]);
    }];

    //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 设置请求方法
    request.HTTPMethod = @"POST";

    //2.2 设置请求体
    request.HTTPBody = [@"username=xiaozhang&pwd=123456&type=JSON" dataUsingEncoding:NSUTF8StringEncoding];

    //3.获得会话对象
    NSURLSession *session = [NSURLSession sharedSession];

    //4.根据会话对象创建Task
    /*
     第一个参数:请求对象
     第二个参数:completionHandler 请求结束的时候调用
     data:响应体信息
     response:响应头信息
     error:错误信息
     completionHandler:该block块在子线程中调用
     */
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

        //6.解析数据
        NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
        NSLog(@"%@",[NSThread currentThread]);
    }];

    //5.执行task
    [dataTask resume];
}
@end


// NSURLSession代理方法
// ViewController.h
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController

@end

// ViewController.m
#import "ViewController.h"

@interface ViewController () <NSURLSessionDataDelegate>

/** 可变的二进制数据*/
@property (nonatomic ,strong) NSMutableData *responseData;

@end

@implementation ViewController

-(NSMutableData *)responseData
{
    if (_responseData == nil) {
        _responseData = [NSMutableData data];
    }
    return _responseData;
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self delegate];
}

- (void)delegate {
    //1.确定请求路径
    NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/login?username=520it&pwd=520it&type=JSON"];
    
    //2.创建请求对象
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    //3.创建会话对象
    //设置代理
    /*
     第一个参数:配置信息 [NSURLSessionConfiguration defaultSessionConfiguration] 默认的
     第二个参数:谁成为代理
     第三个参数:队列 决定代理方法在哪个线程中调用
     */
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    
    //4.创建task
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request];

    //5.执行任务
    [dataTask resume];
}

#pragma mark --------------------
#pragma mark NSURLSessionDataDelegate
//1.接收到服务器的响应
-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
{
    NSLog(@"%s----%@",__func__,[NSThread currentThread]);
    
    //在该方法中需要通过completionHandler回调告诉系统应该如何处理服务器返回的数据
    /*
     NSURLSessionResponseCancel = 0,取消请求任务,不会接收数据
     NSURLSessionResponseAllow = 1,  接收数据
     NSURLSessionResponseBecomeDownload = 2,变成一个下载请求
     NSURLSessionResponseBecomeStream = 3,变成一个stream
     */
    completionHandler(NSURLSessionResponseAllow);
}

//2.接收到服务器返回的数据 可能会被调用多次
-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
    NSLog(@"%s----%@",__func__,[NSThread currentThread]);
    NSLog(@"%@",dataTask.response);
    
    [self.responseData appendData:data];
}

//3.完成或者失败的时候调用
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
     NSLog(@"%s----%@",__func__,[NSThread currentThread]);
    
    //解析数据
    NSLog(@"%@",[[NSString alloc]initWithData:self.responseData encoding:NSUTF8StringEncoding]);
}

@end

上一篇下一篇

猜你喜欢

热点阅读