我正在为 iPhone 编写浏览器。
我在用
NSString* storyHTML = @"";
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request startSynchronous];
下载 HTML。问题是有时 HTTP header 中没有编码,在这种情况下,上面的代码默认为 Latin-ISO。
在这种情况下,我可以读取 HTML 中的 header 并找到指定实际编码的元标记。看起来像这样:
<meta http-equiv="content-type" content="application/xhtml+xml; charset=UTF-8" />
问题是可以在元标记中找到大量可能的编码,如下所示:http://www.iana.org/assignments/character-sets
我需要了解如何将这些编码字符串之一转换为 NSString 类中的常量编码之一:
enum {
NSASCIIStringEncoding = 1,
NSNEXTSTEPStringEncoding = 2,
NSJapaneseEUCStringEncoding = 3,
NSUTF8StringEncoding = 4,
NSISOLatin1StringEncoding = 5, ...
必须有一个类可以为您确定 HTML 的编码方式。有没有办法查看 UIWebView 并了解他们是如何做到的?
看起来下载 HTML 应该很容易,我错过了什么?
谢谢!
最佳答案
只是总结我的评论并在答案中添加一些最后的建议。
评论 1:
从一般用法来看,您可以使用 ASIHTTPRequest
-responseString,否则你可以使用数据本身并使用你自己的逻辑来找出什么类型的编码(UTF8,UTF16等)
评论2:
来自 ASIHTTP 网站:
ASIHTTPRequest will attempt to read the text encoding of the received data from the Content-Type header. If it finds a text encoding, it will set responseEncoding to the appropriate NSStringEncoding. If it does not find a text encoding in the header, it will use the value of defaultResponseEncoding (this defaults to NSISOLatin1StringEncoding). > When you call [request responseString], ASIHTTPRequest will attempt to create a string from the data it received, using responseEncoding as the source encoding.
评论3
另请参阅:Encoding issue with ASIHttpRequest
我个人建议获取响应数据并假设内容适合 UTF16(或 8)。当然,您也可以使用正则表达式或 HTML 解析器来获取 <meta>
<head>
内的标签元素,但如果响应是奇怪的内容类型,那么您可能无法找到字符串 @"<head"
我也会使用 curl
从您计算机上的 CLI 查看 ASIHTTPRequest 正在获取的内容类型。如果你运行这样的命令
curl -I "http://www.google.com/"
您将收到以下响应:
HTTP/1.1 200 OK
Date: Tue, 09 Aug 2011 20:05:00 GMT
Expires: -1
Cache-Control: private, max-age=0
Content-Type: text/html; charset=ISO-8859-1
看起来几乎所有站点都可以正确响应此 header ,如果它们不能正确响应,我认为使用 UTF8 是一个不错的选择。您能否对提出问题的网站链接发表评论?
关于iphone - 编码不存在于 HTTP header 中,如何在 HTML header 中找到它? (iPhone),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6990043/