为URL编码字符串参数 [英] Encoding string arguments for URLs

查看:101
本文介绍了为URL编码字符串参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个为我构建网址的方法。

I created a method to build URLs for me.

- (NSString *)urlFor:(NSString *)path arguments:(NSDictionary *)args
{
    NSString *format = @"http://api.example.com/%@?version=2.0.1";
    NSMutableString *url = [NSMutableString stringWithFormat:format, path];

    if ([args isKindOfClass:[NSDictionary class]]) {
        for (NSString *key in args) {
            [url appendString:[NSString stringWithFormat:@"&%@=%@", key, [args objectForKey:key]]];
        }
    }

    return url;
}



当我尝试构建类似下面的内容时,当然。

When I try to build something like below, the URLs aren't encoded, of course.

NSDictionary *args = [NSDictionary dictionaryWithObjectsAndKeys:
                            @"http://other.com", @"url",
                            @"ABCDEF", @"apiKey", nil];

NSLog(@"%@", [self urlFor:@"articles" arguments:args]);`

返回的值是 http://api.example.com/articles?version=2.0.1&url=http://other.com&apiKey=ABCDEF 应该 http://api.example.com/articles?version=2.0.1&url=http%3A%2F%2Fother.com&apiKey=ABCDEF

The returned value is http://api.example.com/articles?version=2.0.1&url=http://other.com&apiKey=ABCDEF when it should be http://api.example.com/articles?version=2.0.1&url=http%3A%2F%2Fother.com&apiKey=ABCDEF.

我需要对键和值都进行编码。我搜索了一些,发现了 CFURLCreateStringByAddingPercentEscapes stringByAddingPercentEscapesUsingEncoding ,但没有一个测试我工作。

I need to encode both key and value. I searched for something and found CFURLCreateStringByAddingPercentEscapes and stringByAddingPercentEscapesUsingEncoding but none of the tests I made worked.

我如何做什么?

推荐答案

IIRC,斜杠应该在URL的查询部分正确解释。你测试看看它仍然工作没有编码的斜杠?否则,请执行以下操作:

IIRC, slashes should be interpreted properly when they're in the query part of a URL. Did you test to see if it still works without encoded slashses? Otherwise, do something like:

if ([args isKindOfClass:[NSDictionary class]]) {
        for (NSString *key in [args allKeys]) {
            NSString *value = [(NSString*)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)[args objectForKey:key], NULL, CFSTR("/?&:=#"), kCFStringEncodingUTF8) autorelease];
            [url appendString:[NSString stringWithFormat:@"&%@=%@", key, value]];
            [value release];
        }
}

return url;

注意CFURLCreateStringByAddingPercentEscapes的第4个参数的值。

Note the value of the 4th argument to CFURLCreateStringByAddingPercentEscapes.

这篇关于为URL编码字符串参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆