【问题标题】:A single "|" character in the URL breaks loading contents of URL一个“|” URL 中的字符会破坏 URL 的加载内容
【发布时间】:2021-08-15 19:32:00
【问题描述】:

我正在尝试从 Wikipedia API 加载 JSON 格式的文章,但出现以下错误:

nil host used in call to allowsSpecificHTTPSCertificateForHost
nil host used in call to allowsAnyHTTPSCertificateForHost:
NSURLConnection finished with error - code -1002
error when trying to fetch from URL (null) - The file couldn’t be opened.

只有当 URL 字符串包含字符“|”时才会出现这些错误

id=1 (pageids=1) 的文章的网址是:

https://en.wikipedia.org/w/api.php?action=query&format=json&pageids=1&prop=extracts&exintro&explaintext

上面的 URL 不包含字符“I”,所以它可以正常工作。

在维基百科 API 中,您可以通过用“|”分隔它们的 id 来请求多篇文章人物

ids=1,2 和 3 (pageids=1|2|3) 的文章的网址是:

https://en.wikipedia.org/w/api.php?action=query&format=json&pageids=1|2|3&prop=extracts&exintro&explaintext

上面的网址包含“|”性格,一切都失败了。

我使用我在另一篇文章中找到的这个 sn-p 来捕捉错误:

NSError *error = NULL;
NSStringEncoding actualEncoding;

NSString *string = [[NSString alloc] initWithContentsOfURL:url usedEncoding:&actualEncoding error:&error];
if(string)
{
    NSLog( @"hey, I actually got a result of %@", string);

    if(actualEncoding != NSUTF8StringEncoding)
    {
        NSLog( @"and look at that, the actual encoding wasn't NSUTF8StringEncoding");
    }
} else {
    NSLog( @"error when trying to fetch from URL %@ - %@", [url absoluteString], [error localizedDescription]);
}

如果您仔细阅读代码,当有“|”时,url.absoluteString 返回 null里面的人物。

【问题讨论】:

    标签: objective-c nsstring nsurlconnection nsurl nsstringencoding


    【解决方案1】:

    管道 (|) 是一个特殊字符。您必须通过添加适当的百分比编码来对 URL 进行编码。

    这与字符串的文本编码无关。

    NSString * string = @"https://en.wikipedia.org/w/api.php?action=query&format=json&pageids=1|2|3&prop=extracts&exintro&explaintext";
    NSURL *url = [NSURL URLWithString:[string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-31
      • 2013-01-15
      • 2014-03-01
      相关资源
      最近更新 更多