1.本人使用AFNetworking,进行网络解析。在上传用户信息时,携带中文参数时;会导致AFN直接崩溃,显示URL错误!(后来,使用iOS原生也是一样)。
2.
//拼接字符串(其中user,address都是中文)
self.urlString =[NSString stringWithFormat:@"%@p/smart/api/consumer/consumerexp/addConsumerExp?sn=%@&sign=%@&time=%@&sex=%@&age=%@&adds=%@&monicker=%@",self.yuMin,sn,md5,timeString,@"0",_ageTextField.text,_addressTextField.text,_userTextField.text];
//URL转换 使用方法:stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding
//(该方法已在iOS9.0以后被取代)新方法:stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]
self.urlString =[self.urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//然后直接用AFN请求数据(本人下面的使用的是HTTPS 绕过证书的解析方式)
AFHTTPSessionManager * manager =[AFHTTPSessionManager manager];
manager.securityPolicy =[AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
manager.securityPolicy.allowInvalidCertificates =YES;
[manager.securityPolicy setValidatesDomainName:NO];
NSURLSessionDataTask * dataTask;
dataTask =[manager GET: self.urlString parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
NSDictionary *dict =responseObject;
} failure:^(NSURLSessionDataTask *task, NSError *error) {
}];
3.iOS自带网络解析
[NSURLURLWithString:urlString]生成URL对象时,iOS客户端不能正确进行网络请求,网上找到的URLEncode方法又不能完全解决问题.
方法1:
NSString* encodedString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
方法2:
NSString * encodedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,(CFStringRef)urlString,NULL,NULL,kCFStringEncodingUTF8);
这两种方法当urlString里含有中文时URL编码是正确的,但是如果其中含有已转义的%等符号时,又会再次转义而导致错误.
查看方法2参数说明:
CFStringRef CFURLCreateStringByAddingPercentEscapes(CFAllocatorRef allocator,CFStringRef originalString, CFStringRef charactersToLeaveUnescaped, CFStringRef legalURLCharactersToBeEscaped,CFStringEncoding encoding);
因此做出修改,写出方法:
NSString *encodedString = (NSString *)
CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
(CFStringRef)urlString,
(CFStringRef)@"!$&'()*+,-./:;=?@_~%#[]",
NULL,
kCFStringEncodingUTF8);