Objective-C URL编码问题
我正在创建一个URL字符串,如下所示:Objective-C URL编码问题,objective-c,Objective C,我正在创建一个URL字符串,如下所示: [Items appendString:[object objectForKey:@"Items"]]; [Items appendString:@"*"]; [Items deleteCharactersInRange:NSMakeRange([Items length]-1, 1)]; //This returns this: ~SEWER/FLATWORK SUPPLY & INSTALL - 25% of CONTRACT*~SEWER/F
[Items appendString:[object objectForKey:@"Items"]];
[Items appendString:@"*"];
[Items deleteCharactersInRange:NSMakeRange([Items length]-1, 1)];
//This returns this: ~SEWER/FLATWORK SUPPLY & INSTALL - 25% of CONTRACT*~SEWER/FLATWORK SUPPLY & INSTALL - 75% of CONTRACT*SUMP PUMP PIT
//add Items to URL
NSString *fullURL = [NSString stringWithFormat:@"https://example.com?Items=%@, [Items stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
但它的回报是这样的:
Items=~SEWER/FLATWORK%20SUPPLY%20&%20INSTALL%20-%2025%25%20of%20CONTRACT*~SEWER/FLATWORK%20SUPPLY%20&%20INSTALL%20-%2075%25%20of%20CONTRACT*SUMP%20PUMP%20PIT
我如何让它像这样返回:
%20%26%20
而不是%20和的%20和?试试这个
fullURL=[fullURL stringByReplacingOccurrencesOfString:@"&" withString:@"%26"];
NSLog(@"fullURL: %@ ...", fullURL);
使用CFURLCreateStringByAddingPercentEscapes()获取字符的UTF8stringencoding
NSString *urlString = CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef) Items, NULL, CFSTR("!*'();:@&=+$,/?%#[]"), kCFStringEncodingUTF8))
我认为问题是这个方法太聪明了——它只做了获得合法URL所必需的事情,而且因为您的字符串中没有问号,所以它可能认为保留符号是可以的
尝试构建整个URL并对整个URL进行转义
NSString *fullURL = [[@"https://example.com?Items=" stringByAppendingString: items]
stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
或者使用。为什么不使用NSMutableURL
?