English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
IOS solves the problem of Chinese乱码 in URLs
When making an HTTPS connection, the client needs to synthesize a segment of the HTTPS address
If the address contains Chinese characters, the program will crash, and the check found that the reason was that the Chinese characters were not encoded
Found the following two methods in the NSString library
- (NSString *)stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)encoding - (NSString *)stringByReplacingPercentEscapesUsingEncoding:(NSStringEncoding)encoding
I tried it, it works
NSString* string1 = @"https://www.cloudsafe.com/folder"; NSString* string2 = [string1 stringByAddingPercentEscapesUsingEncoding:NSUTF88StringEncoding]; NSString* string3 = [string2 stringByAddingPercentEscapesUsingEncoding:NSUTF88StringEncoding]; NSString* string4 = [string2 stringByReplacingPercentEscapesUsingEncoding:NSUTF88StringEncoding]; NSString* string5 = [string3 stringByReplacingPercentEscapesUsingEncoding:NSUTF88StringEncoding]; NSString* string6 = [string4 stringByReplacingPercentEscapesUsingEncoding:NSUTF88StringEncoding]; NSString* string7 = [string5 stringByReplacingPercentEscapesUsingEncoding:NSUTF88StringEncoding];
Output string1-7结果如下
string1:https://www.cloudsafe.com/文件夹 string2:https://www.cloudsafe.com/%E6%96%87%E4%BB%B6%E5%A4%B9 string3:https://www.cloudsafe.com/%25E6%2596%2587%25E4%25BB%25B6%25E5%25A4%25B9 string4:https://www.cloudsafe.com/文件夹 string5:https://www.cloudsafe.com/%E6%96%87%E4%BB%B6%E5%A4%B9 string6:https://www.cloudsafe.com/文件夹 string7:https://www.cloudsafe.com/文件夹
简单说下我是如何使用的:
在合成URL后, 给整个String转码两次
NSMutableString *address = [[NSMutableString stringWithString:SetNiChengStringWithoutUserNameAndNiCheng] mutableCopy]; address = [[address stringByAppendingString:app.name] mutableCopy]; address = [[address stringByAppendingString:@"/ address = [[address stringByAppendingString:_nameTextField.text] mutableCopy]; address = [[address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] mutableCopy];8StringEncoding] mutableCopy]; address = [[address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] mutableCopy];8StringEncoding] mutableCopy];
On the server side, if it is only simple storage, the server does not need to encode the data into Chinese after receiving the data
When the client requests this part of the data, the client can decode it by itself
After obtaining the string, decode it once to display it normally in Chinese:
str = [str stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding] mutableCopy];8StringEncoding];
Thank you for reading, I hope it can help everyone, thank you for your support to this site!