当查询参数包含&符号时,对NSURL进行编码

时间:2014-05-08 19:48:48

标签: ios objective-c utf-8 nsurl

我正在调用API,有时我的查询参数包含一个&符号。例如,参数可能是name=Billy & Bob

当我创建网址时,我使用:

NSString *url = [NSString stringWithFormat:@"%@/search/%@?name=%@&page=%d", [Statics baseURL], user_id, [term urlEncodeUsingEncoding:NSUTF8StringEncoding], page];
NSURL *fullURL = [NSURL URLWithString:[url stringWithAccessToken]];

我用这种方法编码网址:

-(NSString *)urlEncodeUsingEncoding:(NSStringEncoding)encoding {
    return (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL,
                                                               (CFStringRef)self,
                                                               NULL,
                                                               (CFStringRef)@"!*'\"();:@&=+$,/?%#[]% ",
                                                               CFStringConvertNSStringEncodingToEncoding(encoding)));
}

问题是,&符号通过urlEncodeUsingEncoding方法正确编码,然后URLWithString方法再次对字符串进行编码并替换创建的%个符号在%25的字符串中。

任何人都知道如何编码包含&符号的查询参数?

2 个答案:

答案 0 :(得分:4)

我找到了解决方案,而且是NSURLComponents - 此时在iOS7中添加了一个完全未记录的类。

NSURLComponents *components = [NSURLComponents new];
components.scheme = @"http";
components.host = @"myurl.com";
components.path = [NSString stringWithFormat:@"%@/mypath/%@", @"/mobile_dev/api", user_id];
components.percentEncodedQuery = [NSString stringWithFormat:@"name=%@", [term urlEncodeUsingEncoding:NSUTF8StringEncoding]];

NSURL *fullURL = [components URL];

使用components.percentEncodedQueryterm元素使用我放在其上的编码,而apple不会触及它。

希望这有助于其他人。

答案 1 :(得分:0)

我使用这样的东西:

- (NSString *)URLEncodedStringWithSourceString:(NSString *)sourceString
{
    NSMutableString *output = [NSMutableString string];
    const unsigned char *source = (const unsigned char *)[sourceString UTF8String];
    int sourceLen = strlen((const char *)source);
    for (int i = 0; i < sourceLen; ++i) {
        const unsigned char thisChar = source[i];
        if (thisChar == ' '){
            [output appendString:@"+"];
        } else if (thisChar == '.' || thisChar == '-' || thisChar == '_' || thisChar == '~' || 
                   (thisChar >= 'a' && thisChar <= 'z') ||
                   (thisChar >= 'A' && thisChar <= 'Z') ||
                   (thisChar >= '0' && thisChar <= '9')) {
            [output appendFormat:@"%c", thisChar];
        } else {
            [output appendFormat:@"%%%02X", thisChar];
        }
    }
    return output;
}

希望它有所帮助。