4

我们使用 XML/NSMutableURLRequest 从我们的网站上提取内容,有时它会通过“卷曲”风格的撇号和引号,而不是 '。NSMutableURLRequest 似乎讨厌这些并将它们变成奇怪的 \U00e2\U0080\U0099 字符串。

我可以做些什么来防止这种情况发生吗?我正在使用 GET 方法,所以我应该以某种方式告诉它使用 UTF-8 吗?或者,我错过了什么?

UIApplication* app = [UIApplication sharedApplication];
    app.networkActivityIndicatorVisible = YES;

    NSString *urlStr = [NSString stringWithFormat:@"%@",url];
    NSURL *serviceUrl = [NSURL URLWithString:urlStr];
    NSMutableURLRequest *serviceRequest = [NSMutableURLRequest requestWithURL:serviceUrl];
    [serviceRequest setHTTPMethod:@"GET"];

    NSURLResponse *serviceResponse;
    NSError *serviceError;

    app.networkActivityIndicatorVisible = NO;

    return [NSURLConnection sendSynchronousRequest:serviceRequest returningResponse:&serviceResponse error:&serviceError];
4

3 回答 3

5

NSURLConnection返回NSData响应。您可以获取该NSData响应并将其转换为字符串。然后取这个字符串,把它转回一个NSData对象,一路正确地 UTF-8 编码,然后把它提供给NSXMLParser.

示例:(假设responseNSData您请求的响应)

// long variable names for descriptive purposes
NSString* xmlDataAsAString = [[[NSString alloc] initWithData:response] autorelease];
NSData* toFeedToXMLParser = [xmDataAsAString dataUsingEncoding:NSUTF8StringEncoding];
NSXMLParser* parser = [[[NSXMLParser alloc] initWithData:toFeedToXMLParser] autorelease];
// now utilize parser...
于 2011-01-28T03:47:34.120 回答
0

我建议使用替换那些字符stringByReplacingCharactersInRange:withString:来替换不需要的字符串。

NSString *currentTitle = @"Some string with a bunch of stuff in it.";

//Create a new range for each character.
NSRange rangeOfDash = [currentTitle rangeOfString:@"character to replace"];
NSString *location = (rangeOfDash.location != NSNotFound) ? [currentTitle substringToIndex:rangeOfDash.location] : nil;

if(location){
    currentTitle = [[currentTitle stringByReplacingOccurrencesOfString:location withString:@""] mutableCopy];
}

我过去曾这样做以处理您描述的相同问题。

于 2011-01-25T18:59:00.050 回答
0

尝试使用 stringByReplacingPercentEscapesUsingEncoding:

于 2011-01-25T18:59:38.833 回答