iOS开发 系统原生NSURLSessionDataTask、NSURLConnection网络请求(POST)

NSURLSessionDataTask网络请求(POST)

- (void)NSURLSessionNetworkRequest

{

NSURL *nsurl = [NSURL URLWithString:@"www.baidu.com"];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:nsurl];

    //如果想要设置网络超时的时间的话,可以使用下面的方法:

    //NSMutableURLRequest *mutableRequest=[NSMutableURLRequest requestWithURL:nsurl cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];


    //设置请求类型

    request.HTTPMethod = @"POST";


    //将需要的信息放入请求头

//    [request setValue:@"xxx" forHTTPHeaderField:@"Authorization"];//token

//    [request setValue:@"xxx" forHTTPHeaderField:@"Gis-Lng"];//坐标 lng

//    [request setValue:@"xxx" forHTTPHeaderField:@"Gis-Lat"];//坐标 lat

//    [request setValue:@"xxx" forHTTPHeaderField:@"Version"];//版本

//    NSLog(@"POST-Header:%@",request.allHTTPHeaderFields);


    //把参数放到请求体内

    NSString *postStr = [self parseParams:params];

    request.HTTPBody = [postStr dataUsingEncoding:NSUTF8StringEncoding];


    NSURLSession *session = [NSURLSession sharedSession];

    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {


        if (error) { //请求失败

            NSLog(@"请求失败");

        } else {  //请求成功

            NSDictionary * responseDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];

            NSLog(@"%@", responseDict);

        }

    }];

    [dataTask resume];  //开始请求

}

//重新封装参数 加入app相关信息

- (NSString *)parseParams:(NSDictionary *)params

{

    NSMutableDictionary *parameters = [[NSMutableDictionary alloc] initWithDictionary:params];

    NSLog(@"请求参数:%@",parameters);   


    NSString *keyValueFormat;

    NSMutableString *result = [NSMutableString new];

    //实例化一个key枚举器用来存放dictionary的key


    //加密处理 将所有参数加密后结果当做参数传递

    //parameters = @{@"i":@"加密结果 抽空加入"};


    NSEnumerator *keyEnum = [parameters keyEnumerator];

    id key;

    while (key = [keyEnum nextObject]) {

        keyValueFormat = [NSString stringWithFormat:@"%@=%@&", key, [params valueForKey:key]];

        [result appendString:keyValueFormat];

    }

    return result;

}



NSURLConnection网络请求

- (void)NSURLConnectionNetworkRequest {

    /*

    // 1.根据网址初始化OC字符串对象

    NSString *urlStr = @"www.baidu.com";

    // 2.创建NSURL对象

    NSURL *url = [NSURL URLWithString:urlStr];

    // 3.创建请求

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

    // 4.创建参数字符串对象

    NSString *parmStr = @"grade_id=10&class_id=209&student_id=7";

    // 5.将字符串转为NSData对象

    NSData *pramData = [parmStr dataUsingEncoding:NSUTF8StringEncoding];

    // 6.设置请求体

    [request setHTTPBody:pramData];

    // 7.设置请求方式

    [request setHTTPMethod:@"POST"];


    // 创建同步链接

    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

    */


    // POST请求

    NSString *urlString = @"www.baidu.com";

    //创建url对象

    NSURL *url = [NSURL URLWithString:urlString];

    //创建请求

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10];

    //创建参数字符串对象

    NSString *parmStr = @"grade_id=10&class_id=209&student_id=7";

    //将字符串转换为NSData对象

    NSData *data = [parmStr dataUsingEncoding:NSUTF8StringEncoding];

    [request setHTTPBody:data];

    [request setHTTPMethod:@"POST"];

    //创建异步连接(形式二)

    [NSURLConnection connectionWithRequest:request delegate:self];

}

//代理方法 服务器接收到请求时

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response

{

}

// 当收到服务器返回的数据时触发, 返回的可能是资源片段

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

{

    NSLog(@"%ld == %@", [data length], data);

NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];

    NSLog(@"%@", dic);

}

// 当服务器返回所有数据时触发, 数据返回完毕

- (void)connectionDidFinishLoading:(NSURLConnection *)connection

{

    NSLog(@"返回完成");

}

// 请求数据失败时触发

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error

{

    NSLog(@"%s", __FUNCTION__);

}

你可能感兴趣的