iOS关于/的坑
程序员文章站
2024-01-21 20:31:52
...
今天和服务端对接的时候遇到两个和 “/”(斜杠)有关的坑。
一、encode相关
NSString 的 stringByAddingPercentEscapesUsingEncoding 可以对 url 参数进行编码,但不会对所有字符都编码,比如说 “/”
// encodedUrl为/test/test
NSString *testString = @"/test/test";
NSString *encodedUrl = [testString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
解决方案:
// encodedUrl为%2Ftest%2Ftest
NSString *testString = @"/test/test";
NSString *charactersToEscape = @"?!@#$^&%*+,:;='\"`<>()[]{}/\\| ";
NSCharacterSet *allowedCharacters = [[NSCharacterSet characterSetWithCharactersInString:charactersToEscape] invertedSet];
NSString *encodedUrl = [testString stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacters];
二、Json相关
系统NSJSONSerialization序列化,会转义”/”为”\/”。
解决方案:
NSData *bodyData = [NSJSONSerialization dataWithJSONObject:@{@"m":@"/test/test"} options:self.writingOptions error:error];
NSString *jsonString = [[NSString alloc] initWithData:bodyData encoding:NSUTF8StringEncoding];
jsonString = [jsonString stringByReplacingOccurrencesOfString:@"\\" withString:@""];
[jsonString dataUsingEncoding:NSUTF8StringEncoding];