(转)iOS 网络请求汇总

原生session的GET请求

   //入参拼接(?衔接),参用&分割
    NSString *urlstring=@"http://121.43.59.5:8012/GetToken.aspx?username=123";
    /*如果URL网址里有中文,要先转成utf8编码(如百度天气接口)
     NSString *urlstring=[NSString stringWithFormat:@"http://api.map.baidu.com/telematics/v3/weather?location=北京&output=json&ak=%@&mcode=%@",ak,mcode];
    NSString *urlstr=[urlstring stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
     */
    NSURL *url = [NSURL URLWithString:urlstring];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSURLSessionDataTask *dataTask = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        //获取的内容是字符串
        NSString *str=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"%@",str);
    }];
    [dataTask resume];

原生session的POST请求

  //1.创建会话对象
    NSURLSession *session = [NSURLSession sharedSession];
    //2.根据会话对象创建task
    NSURL *url = [NSURL URLWithString:@"http://121.43.59.5:8011/httptest.aspx"];
    //3.创建可变的请求对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //4.修改请求方法为POST
    request.HTTPMethod = @"POST";
    [request setValue:@"application/json;encoding=utf-8" forHTTPHeaderField:@"Content-Type"];
    //5.设置请求体
    NSString *prame = [NSString stringWithFormat:@"test=123"];
    request.HTTPBody = [prame dataUsingEncoding:NSUTF8StringEncoding];
    //6.根据会话对象创建一个Task(发送请求)
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error){
        //8.解析数据
        //根据后端数据解析
        NSString *str=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        //NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
        NSLog(@"%@",str);
        /* dispatch_async(dispatch_get_main_queue(), ^{
                    网络请求自动开启在子线程,UI刷新的代码需要回到主线程操作
                });
        */
    }];
    //7.执行任务
    [dataTask resume];
#pragma mark NSURLSessionDataDelegate
//如果发送的请求是https的,那么才会调用该方法,(需要遵循代理)
//challenge 质询,挑战
//NSURLAuthenticationMethodServerTrust
-(void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler
{
    //如果不是服务器证书直接返回
    if(![challenge.protectionSpace.authenticationMethod isEqualToString:@"NSURLAuthenticationMethodServerTrust"])
    {
        return;
    }
    NSLog(@"%@",challenge.protectionSpace);
    //NSURLSessionAuthChallengeDisposition 如何处理证书
    /*
     NSURLSessionAuthChallengeUseCredential = 0, 使用该证书 安装该证书
     NSURLSessionAuthChallengePerformDefaultHandling = 1, 默认采用的方式,该证书被忽略
     NSURLSessionAuthChallengeCancelAuthenticationChallenge = 2, 取消请求,证书忽略
     NSURLSessionAuthChallengeRejectProtectionSpace = 3,          拒绝
     */
    NSURLCredential *credential = [[NSURLCredential alloc]initWithTrust:challenge.protectionSpace.serverTrust];

    //NSURLCredential 授权信息
    completionHandler(NSURLSessionAuthChallengeUseCredential,credential);
}

AFN的GET网络请求如下:

NSString *urlstring=@"http://120.25.226.186:32812/login";
    NSDictionary *param=@{@"username": @"520it",
                          @"pwd":@"520it"};
    //1、创建管理者(AFHTTPSessionManager内部基于NSURLSession实现)
    AFHTTPSessionManager *manger=[AFHTTPSessionManager manager];
    /*序列化处理
     设置AFN采用什么样的方式来解析服务器返回的数据, 默认采用json方式解析数据
     //如果返回的是XML,那么告诉AFN,响应的时候使用XML的方式解析
     manager.responseSerializer = [AFXMLParserResponseSerializer serializer];

     //如果返回的就是二进制数据,那么采用默认二进制的方式来解析数据
     //manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    //采用JSON的方式来解析数据
    //manager.responseSerializer = [AFJSONResponseSerializer serializer];
     */
    manger.responseSerializer=[AFHTTPResponseSerializer serializer];
    /*
     requestSerializer:请求数据格式,默认是二进制的HTTP
     manger.requestSerializer=[AFHTTPRequestSerializer serializer];
     manger.requestSerializer=[AFJSONRequestSerializer serializer];
     manger.requestSerializer=[AFXMLRequestSerializer serializer];
     */
    [manger GET:urlstring parameters:param progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSString *str=[[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        //NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"%@",str);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求失败");
    }];

AFN POST请求

NSString *urlstr=@"http://120.25.226.186:32812/login";
    NSDictionary *param=@{@"username": @"520it",
                          @"pwd":@"520it"
                          };
    AFHTTPSessionManager *manger=[AFHTTPSessionManager manager];
    manger.responseSerializer=[AFHTTPResponseSerializer serializer];
    [manger POST:urlstr parameters:param progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSString *str=[[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSLog(@"%@",str);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求失败");
    }];
//AFN对https的处理
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

    //更改解析方式(默认为json解析,此次请求为网址源码)
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

    //设置对证书的处理方式
    //接受无效证书,默认为NO
    manager.securityPolicy.allowInvalidCertificates = YES;
    //对域名的检测,默认为YES
    manager.securityPolicy.validatesDomainName = NO;

    [manager GET:@"https://kyfw.12306.cn/otn" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"success---%@",[[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding]);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"error---%@",error);
    }];

原文地址:http://www.jianshu.com/p/28cc386fd460
原文更加详细,总结的更加完整,我仅仅使用了上述几种请求,复制此文里留用....

你可能感兴趣的:((转)iOS 网络请求汇总)