我试图在URL中有垂直管道
输入字符串:http://testURL.com/Control?command=dispatch|HOME|ABC:用户名
-(NSString *)getURLEncodedString:(NSString *)stringvalue{
NSMutableString *output = [NSMutableString string];
const unsigned char *source = (const unsigned char *)[stringvalue UTF8String];
int sourceLen = strlen((const char *)source);
for (int i = 0; i < sourceLen; ++i) {
const unsigned char thisChar = source[i];
if (thisChar == ':' || thisChar == '/' || thisChar == '?' || thisChar == '=' || thisChar == '|' || 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;
}
调用上述方法后输出字符串:http://testURL.com/Control?command=dispatch|HOME|ABC:User%20Name
现在,如果我将上面的编码字符串传递给[[NSURL URLWithString:encodedString];
我得到域名=NSURLErrorDomain Code=-1000 "坏URL" UserInfo=0xae9d760 {NSUnderlyingError=0xaec8ed0 "坏URL", NSLocalizedDescription=坏URL}
有关于这个的输入吗?我希望URL看起来像encodedString.
谢谢!
我真的看不到手动编码/转义字符串的理由…无论如何,这将工作得很好:
NSString *urlString = @"http://testURL.com/Control?command=dispatch|HOME|ABC:User Name";
NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
输出:http://testURL.com/Control?command=dispatch%7CHOME%7CABC:User%20Name
似乎NSURL
不喜欢竖条毕竟,你没有在你的方法中编码,从而得到一个bad URL
代码。