iOS:如何进行正确的URL编码?

时间:2012-09-29 11:40:48

标签: ios url-encoding

我无法打开UIWebView的网址,所以我已经预先找到了&发现我需要对URL进行编码,所以我尝试对其进行编码,但是我在URL编码方面遇到了问题:我的网址是http://somedomain.com/data/Témp%20Page%20-%20Open.html(这不是真正的网址)。

我担心%20我尝试使用stringByReplacingOccuranceOfString:@"" withString:@""替换它,它会给我一个我想要的网址http://somedomain.com/data/Témp Page - Open.html但是它不会在UIWebView中打开但是令人惊讶地它在Safari& FireFox完美。即使我打开未编码的URL,它也会自动转换并打开我正在寻找的页面。

我已经谷歌搜索URL编码&它指出了我已经检查过的不同结果,但没有结果帮助我!我在不同的URL编码问题中尝试了不同的函数答案,但它只是更改了所有特殊字符,并使我的网址http%3A%2F%2Fsomedomain.com%2Fdata%2FT...无法在UIWebView甚至在任何浏览器中打开。

它在Error Log

中提供了以下UIWebView delegate
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error { }
  

错误代码:101    &安培;说明:错误Domain = WebKitErrorDomain Code = 101“无法完成操作。(WebKitErrorDomain错误101.)”UserInfo = 0x6e4cf60 {}

10 个答案:

答案 0 :(得分:16)

@Dhaval Vaishnani提供的答案只是部分正确。此方法将?=&字符视为不进行编码,因为它们在URL中有效。因此,要编码任意字符串以安全地用作URL的一部分,您不能使用此方法。相反,你必须回归使用CoreFoundation和CFURLRef

NSString *unsafeString = @"this &string= confuses ? the InTeRwEbZ";
CFStringRef safeString = CFURLCreateStringByAddingPercentEscapes (
    NULL,
    (CFStringRef)unsafeString,
    NULL,
    CFSTR("/%&=?$#+-~@<>|\\*,.()[]{}^!"),
    kCFStringEncodingUTF8
);

不要忘记使用CFRelease(safeString);处理结果字符串的所有权。

此外,似乎尽管标题,OP正在寻找解码而不是编码字符串。 CFURLRef有另一个类似的函数调用用于此:

NSString *escapedString = @"%32%65BCDEFGH";
CFStringRef unescapedString = CFURLCreateStringByReplacingPercentEscapesUsingEncoding (
    NULL,
    (CFStringRef)escapedString,
    CFSTR(""),
    kCFStringEncodingUTF8
);

同样,不要忘记正确的内存管理。

答案 1 :(得分:14)

我做了一些测试,我认为问题不在于UIWebView,而是由于“Témp”中的é未正确编码,NSURL将不接受该网址。这将导致+[NSURLRequest requestWithURL:]-[NSURL URLWithString:]返回nil,因为该字符串包含格式错误的网址。我想你最后使用nil请求-[UIViewWeb loadRequest:]这是不合适的。

示例:

NSLog(@"URL with é: %@", [NSURL URLWithString:@"http://host/Témp"]);
NSLog(@"URL with encoded é: %@", [NSURL URLWithString:@"http://host/T%C3%A9mp"]);

输出:

2012-10-02 12:02:56.366 test[73164:c07] URL with é: (null)
2012-10-02 12:02:56.368 test[73164:c07] URL with encoded é: http://host/T%C3%A9mp

如果你真的想借用WebKit所具有的格式错误的URL的优雅处理而不想自己实现它,你可以做这样的事情,但它非常难看:

UIWebView *webView = [[[UIWebView alloc]
                       initWithFrame:self.view.frame]
                      autorelease];

NSString *url = @"http://www.httpdump.com/texis/browserinfo/Témp.html";

[webView loadHTMLString:[NSString stringWithFormat:
                         @"<script>window.location=%@;</script>",
                         [[[NSString alloc]
                           initWithData:[NSJSONSerialization
                                         dataWithJSONObject:url
                                         options:NSJSONReadingAllowFragments
                                         error:NULL]
                           encoding:NSUTF8StringEncoding]
                          autorelease]]
                baseURL:nil];

答案 2 :(得分:13)

最直接的方法是使用:

NSString *encodedString = [rawString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

iDhaval很接近,但他反过来这样做(解码而不是编码)。

Anand的方式可行,但你很可能不得不替换空格和换行符。请参阅此处的参考: http://en.wikipedia.org/wiki/Percent-encoding#Percent-encoding_reserved_characters

希望有所帮助。

答案 3 :(得分:6)

在iPhone中对URL进行编码非常简单。它如下

NSString* strURL = @"http://somedomain.com/data/Témp Page - Open.html";

NSURL* url = [NSURL URLWithString:[strURL stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

这是对网址进行编码的完美方式,我正在使用它,它与我完美配合。

希望它能帮到你!!!

答案 4 :(得分:4)

对于能够针对此问题进行网址编码的人来说,这可能很有用,因为我的问题可能与已经解决和接受的不同,这就是我以前编码的方式,

-(NSString *)encodeURL:(NSString *)urlString
{
    CFStringRef newString = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)urlString, NULL, CFSTR("!*'();:@&=+@,/?#[]"), kCFStringEncodingUTF8);
    return (NSString *)CFBridgingRelease(newString);
}

答案 5 :(得分:3)

你可以试试这个

NSString *url = @"http://www.abc.com/param=Hi how are you";

NSString* encodedUrl = [url stringByAddingPercentEscapesUsingEncoding:
 NSASCIIStringEncoding];

答案 6 :(得分:2)

我认为这对你有用

[strUrl stringByAddingPercentEncodingWithAllowedCharacters:NSCharacterSet.URLQueryAllowedCharacterSet]

用于URL编码的Native方法。

答案 7 :(得分:0)

您可能需要将URL分解为其组成部分,然后对主机和路径进行URL编码,而不是对方案进行URL编码。然后再把它重新组合在一起。

使用字符串创建NSURL,然后使用其上的方法(如主机,方案,路径,查询等)将其拉开。然后使用CFURLCreateStringByAddingPercentEscapes对零件进行编码,然后将它们重新组合到一个新的NSURL中。

答案 8 :(得分:0)

Swift 4.x

let originalString = "https://www.somedomain.com/folder/some cool file.jpg"
let escapedString = originalString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
print(escapedString!)

答案 9 :(得分:-1)

请你试试这个。

    //yourURL contains your Encoded URL
    yourURL = [yourURL stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
    yourURL = [yourURL stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    NSLog(@"Keyword:%@ is this",yourURL);

我不确定,但在我的情况下我已经解决了这个问题。 希望这能解决你的问题。