iphone - 编码不存在于 HTTP header 中,如何在 HTML header 中找到它? (iPhone)

标签 iphone html encoding content-type

我正在为 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/

相关文章:

javascript - 从输入值创建 li 元素

javascript - 查找展开元素的父级并使用 jquery 在 .wrap() 中使用它

java - 将响应从 ServerResource 流式传输回客户端

ios - 如何删除现有记录并在核心数据中添加新数据

iphone - 如何改善我的应用程序的启动时间?

ios - 在 iPhone 上调试 iOS 应用程序时遇到问题

iphone - 在 NSMutableDictionary 中存储变量值

Html/css 高度与其他 div 不同

animation - GIFEncoder.Class.php 和一个无循环 GIF 动画

angularjs - 在 Tomcat 上读取 UTF-8 请求的问题