美文网首页
AFN以header、body传参方式请求服务器

AFN以header、body传参方式请求服务器

作者: A_Yun | 来源:发表于2023-08-13 11:34 被阅读0次

    需求:
    指定参数放到header和body

    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:@"" forKey:@"token"];
    [params setObject:@"" forKey:@"reqid"];
    
    NSString *url = @"";
    NSMutableDictionary *parameterDict = [NSMutableDictionary dictionaryWithDictionary:params];
        NSMutableDictionary *parameterToken = [NSMutableDictionary dictionary];
        if ([[parameterDict allKeys] containsObject:@"token"]) {
            [parameterToken setObject:parameterDict[@"token"] forKey:@"token"];
            [parameterDict removeObjectForKey:@"token"];
        }
        
    //参数转成二进制
    NSString *jsonString = [self convertToJSONData:parameterDict.mutableCopy];
    NSData *dataBody = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    AFHTTPResponseSerializer *responseSerializer = [AFHTTPResponseSerializer serializer];
        responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", @"text/json", @"text/javascript", @"text/plain", @"application/javascript", nil];
        manager.responseSerializer = responseSerializer;
    
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:url parameters:nil error:nil];
    request.timeoutInterval = 60.f;
    //请求头
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:ReturnValidString(params[@"token"]) forHTTPHeaderField:@"token"];
    //请求体
    [request setHTTPBody:dataBody];
    
    NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromData:nil progress:^(NSProgress * _Nonnull uploadProgress) {
            // 计算进度
            float progress = (float)uploadProgress.totalUnitCount / uploadProgress.completedUnitCount;
            NSLog(@"上传进度:%.f",progress);
        } completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
            if (!error) {
                //解析
                NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];  
    
                NSLog(@"结果:%@",jsonData);
                //resultCode = 0000表示已请求成功
                if ([jsonData[@"resultCode"] isEqualToString:@"0000"]) {
                    if (success) {
                        success(jsonData);
                    }
                }
            } else {
                NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil]; 
                NSLog(@"错误:%@",error);
                if (failure) {
                    failure(error);
                }
            }
        }];
        [uploadTask resume];
    
    /// NSDictionary 转化为 NSString
    - (NSString*)convertToJSONData:(id)infoDict {
        NSError *error;
        //如果您不关心生成的字符串的可读性,则传递 0 (options:0)
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:infoDict options:NSJSONWritingPrettyPrinted error:&error];
        NSString *jsonString = @"";
        if (!jsonData){
            NSLog(@"Got an error: %@", error);
        }else{
            jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        }
        
        jsonString = [jsonString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];  //去除掉首尾的空白字符和换行字符
        jsonString = [jsonString stringByReplacingOccurrencesOfString:@"\n" withString:@""];
        jsonString = [jsonString stringByReplacingOccurrencesOfString:@" " withString:@""];// 去掉空格
        //jsonString = [jsonString stringByReplacingOccurrencesOfString:@"\\" withString:@""];// 去掉斜杠
        return jsonString;
    }
    

    相关文章

      网友评论

          本文标题:AFN以header、body传参方式请求服务器

          本文链接:https://www.haomeiwen.com/subject/dkbfmdtx.html