0

我正在尝试在 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];

我得到 Domain=NSURLErrorDomain Code=-1000 "bad URL" UserInfo=0xae9d760 {NSUnderlyingError=0xaec8ed0 "bad URL", NSLocalizedDescription=bad URL}

对这家伙有什么意见吗?我希望 URL 看起来像编码字符串。

谢谢!

4

1 回答 1

2

我真的看不出手动编码/转义字符串的理由......无论如何,这都会很好地工作:

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代码。

于 2013-06-06T13:45:07.710 回答