【发布时间】:2010-09-28 20:10:27
【问题描述】:
我遇到了 ASIHttpRequest 的编码问题。当我得到一个 URL 时,除了一点编码问题之外,数据都完美返回。
这是我的代码:
- (void)fetchGamesForCategory
{
NSString *url_string = [[NSString alloc] initWithFormat:url_match, theCategory._id];
NSURL *url = [NSURL URLWithString:url_string];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request startSynchronous];
NSError *error = [request error];
if (!error) {
NSString *response = [request responseString];
NSLog(@"response: %@", response);
NSData *data = [response dataUsingEncoding:NSUTF8StringEncoding];
NSString *errorDesc = nil;
NSPropertyListFormat format;
NSDictionary * dict = (NSDictionary*)[NSPropertyListSerialization
propertyListFromData:data
mutabilityOption:NSPropertyListMutableContainersAndLeaves
format:&format
errorDescription:&errorDesc];
NSDictionary *categoryListPathDictionary = [[NSDictionary alloc] initWithDictionary:dict];
categoryMatchList *categoryMatchListFile = [[[categoryMatchList alloc] initWithDictionary:categoryListPathDictionary] retain];
matchArray = [categoryMatchListFile getMatchListXmlSet];
[self loadPage];
}
}
这是我的结果:
2010-09-28 21:49:35.970 oddsApp[46429:190f] response: <?xml version="1.0" encoding="UTF-8"?><!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist>
<dict>
<key>matches</key>
<array>
<dict>
<key>name</key>
<string>Gais - Häcken</string>
<key>date</key>
<string>2010-09-29 18:00</string>
<key>id</key>
<string>156</string>
<key>odds</key>
<dict>
<key>1</key>
<string>2.6</string>
<key>X</key>
<string>3.28</string>
<key>2</key>
<string>2.862</string>
</dict>
</dict>
</array>
</dict>
</plist>
如您所见,<string>Gais - Häcken</string> 的编码被搞砸了,尽管在浏览器中显示页面时它是正确的:
有人知道怎么回事吗?
【问题讨论】:
-
ASIHTTPRequest 中的可爱评论:“// 如果 Content-Type 标头指定了编码,我们将使用它,否则我们使用 defaultStringEncoding(默认为 NSISOLatin1StringEncoding)”。这在技术上对 HTTP 是正确的(文本编码默认为 ISO-8859-1),但与其他人所做的不匹配。你可以做
[request setResponseEncoding:NSUTF8StringEncoding],但这有点小技巧。 -
是的,我读过,但我想我理解得不够好。我搜索了“setEncoding”,但现在我知道为什么没有找到。谢谢。
标签: iphone encoding ios4 plist asihttprequest