美文网首页
AFHTTPSessionManager传输中文乱码问题

AFHTTPSessionManager传输中文乱码问题

作者: Transport丶RNA | 来源:发表于2020-09-17 17:28 被阅读0次

使用字典存在的问题

NSMutableDictionary中通过
[dict setObject:@"value" forKey:@"key"];
设置中文时,OC回自动将值的编码设置为UTF-8,无论你在设值前如何强制编码格式为gbk都无效,此时如果服务器接受参数时取值编码为gbk,中文将会乱吗

解决方式

  • JSON传值
NSString *postStr = [NSString stringWithFormat:@"requestType=%@&requestId=%@", requestType, requestId];
NSString *urlString = [NSString stringWithFormat:@"服务器地址",_postUrl.text];
    NSMutableDictionary *resultDic = [NSMutableDictionary dictionary];
    NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    [urlRequest setHTTPMethod: @"POST"];
    [urlRequest setHTTPBody:[postStr dataUsingEncoding:gbk]];
    [urlRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html",@"text/json",@"text/plain",@"text/text",@"text/javascript",nil];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

    NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:urlRequest completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        NSStringEncoding gbk = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
        NSString *gbkStr = [[NSString alloc]initWithData:responseObject encoding:gbk];
        NSData *jsonData = [gbkStr dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
        [resultDic setDictionary:dic];
        if([resultDic objectForKey:@"result"]!=nil && ![[resultDic objectForKey:@"result"] isEqual:[NSNull null]]){
            NSString *result = [resultDic objectForKey:@"result"];  }
        }];
    [dataTask resume];

相关文章

网友评论

      本文标题:AFHTTPSessionManager传输中文乱码问题

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