(使用NSData
)您可以將1.0
替換爲1%2E0
,將|
替換爲%7C
。可能的是,與所述週期被解釋爲具有擴展(From Foundation Constants Reference)的文件,因此,258的錯誤:
NSError Codes
NSError codes in the Cocoa error domain.
enum {
...
NSFileReadInvalidFileNameError = 258,
}
NSFileReadInvalidFileNameError: Read error because of an invalid file name Available in Mac OS X v10.4 and later. Declared in FoundationErrors.h.
嘗試這種情況:
- (void)viewDidLoad {
[super viewDidLoad];
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"https://ajax.googleapis.com/ajax/services/language/translate?v=1%2E0&q=abdicate&langpair=en%7Ces"]];
if (data) {
NSLog([[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]);
}
}
給人的輸出:
2011-09-27 15:38:05.691 Project[44290:fb03] {"responseData": {"translatedText":"abdicar"}, "responseDetails": null, "responseStatus": 200}
這與您在瀏覽器中導航到網址https://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=abdicate&langpair=en|es所得到的結果相同。
嘗試使用NSData的,然後轉換成字符串,像這樣:
NSString *result;
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"https://ajax.googleapis.com/ajax/services/language/translate?%@", [self urlencode:@"v=1.0&q=abdicate&langpair=en|es"]]]];
if (data) {
result = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
} else {
// Do something
}
這是上面所用的進行urlencode方法:
- (NSString *)urlencode:(NSString *)str {
NSMutableString *output = [NSMutableString string];
const unsigned char *source = (const unsigned char *)[str UTF8String];
int sourceLen = strlen((const char *)source);
for (int i = 0; i < sourceLen; ++i) {
const unsigned char thisChar = source[i];
if (thisChar == ' '){
[output appendString:@"+"];
} else if (thisChar == '.' || thisChar == '-' || thisChar == '_' || thisChar == '~' ||
(thisChar >= 'a' && thisChar <= 'z') ||
(thisChar >= 'A' && thisChar <= 'Z') ||
(thisChar >= '0' && thisChar <= '9')) {
[output appendFormat:@"%c", thisChar];
} else {
[output appendFormat:@"%%%02X", thisChar];
}
}
return output;
}
這整個部分是不必要的,只需要更換即可1.0和|而不是編碼整個網址。
嘗試'NSData'用'1%2E0'替換'1.0',用'%7C'替換'|'。 – chown