我目前正在尝试将一个URL放在一起,我指定了一些GET参数.但是我想在这个URL中使用日语或其他字符. 有没有办法将NSString转换为包含我的NSString中“特殊”字符的HTML实体的字符串? 我目前
有没有办法将NSString转换为包含我的NSString中“特殊”字符的HTML实体的字符串?
我目前正在使用以下代码,除了中文和日文等“特殊字符”之外,它似乎有效:
NSString* url = @"/translate_a/t?client=t&sl=auto&tl="; url = [url stringByAppendingString:destinationLanguage]; url = [url stringByAppendingString:@"&text="]; url = [url stringByAppendingString:text]; NSURL* nsurl = [[NSURL alloc] initWithScheme:@"http" host:@"translate.google.com" path:url]; NSError* error; NSString* returnValue = [[NSString alloc] initWithContentsOfURL:nsurl encoding:NSUTF8StringEncoding error:&error];要对参数进行正确的URL编码,您需要将每个名称和值转换为UTF-8,然后分别对每个名称和值进行URL编码,然后使用“&”使用“=”和名称 – 值对连接名称.
我通常发现将所有参数放在NSDictionary中更容易,然后从字典中构建查询字符串.这是我用来做的一个类别:
// file NSDictionary+UrlEncoding.h #import <Cocoa/Cocoa.h> @interface NSDictionary (UrlEncoding) -(NSString*) urlEncodedString; @end // file NSDictionary+UrlEncoding.m #import "NSDictionary+UrlEncoding.h" // private helper function to convert any object to its string representation static NSString *toString(id object) { return [NSString stringWithFormat: @"%@", object]; } // private helper function to convert string to UTF-8 and URL encode it static NSString *urlEncode(id object) { NSString *string = toString(object); return [string stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]; } @implementation NSDictionary (UrlEncoding) -(NSString*) urlEncodedString { NSMutableArray *parts = [NSMutableArray array]; for (id key in self) { id value = [self objectForKey: key]; NSString *part = [NSString stringWithFormat: @"%@=%@", urlEncode(key), urlEncode(value)]; [parts addObject: part]; } return [parts componentsJoinedByString: @"&"]; } @end
该方法构建一个名称 – 值对的数组,通过URL对每个键和值进行编码,然后将它们与’=’连接在一起.然后零件阵列中的零件与’&’连接在一起字符.
所以对于你的例子:
#import "NSDictionary+UrlEncoding.h" // ... NSMutableDictionary *parameters = [NSMutableDictionary dictionary]; [parameters setValue: @"t" forKey: @"client"]; [parameters setValue: @"auto" forKey: @"sl"]; [parameters setValue: destinationLanguage forKey: @"tl"]; [parameters setValue: text forKey: @"text"]; NSString *urlString = [@"/translate_a/t?" stringByAppendingString: [parameters urlEncodedString]];