今天在一个项目里面后台是个比较老的Java开发人员,编码方式不是utf-8而是gbk格式的,踩了很多坑记录一下给Java传递json数据gbk编码的处理:
NSString * urlStr = @"http://你的服务器地址";
NSError *error;
NSDictionary*dic1=@{@"userId":@"110"
};
NSData *jsonData1 = [NSJSONSerialization dataWithJSONObject:dic1 options:0 error:&error];
NSString *jsonString1 = [[NSString alloc] initWithData:jsonData1 encoding:NSUTF8StringEncoding];
NSDictionary*body=@{
@"data":jsonString1,
@"requestCode":@"110"
};
NSError *error1;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:body options:0 error:&error1];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
[urlRequest setHTTPMethod: @"POST"];
//转成gbk编码传递给后台
[urlRequest setHTTPBody:[jsonString dataUsingEncoding:enc]];
[urlRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
AFHTTPSessionManager *mgr8 = [AFHTTPSessionManager manager];
mgr8.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html",@"text/json",@"text/plain",@"text/text",@"text/javascript",nil];
mgr8.requestSerializer = [AFHTTPRequestSerializer serializer];
mgr8.responseSerializer = [AFHTTPResponseSerializer serializer];
NSURLSessionDataTask *dataTask = [mgr8 dataTaskWithRequest:urlRequest completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
//声明一个gbk编码类型
NSStringEncoding gbkEncoding = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
// 使用如下方法 将获取到的数据按照gbkEncoding的方式进行编码,结果将是正常的汉字
NSString *zhuanHuanHouDeShuJu = [[NSString alloc] initWithData:responseObject encoding:gbkEncoding];
NSLog(@"%@",zhuanHuanHouDeShuJu);
//再转换成想要的json数据
NSData *jsonData = [zhuanHuanHouDeShuJu dataUsingEncoding:NSUTF8StringEncoding];
NSError *err;
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
options:NSJSONReadingMutableContainers
error:&err];
NSLog(@"最终的json数据为%@",dic);
}];
[dataTask resume];
这样就解决了给Java传递gbk编码格式的json数据了
网友评论