【问题标题】:Objective C URL with Vertical pipes/bars带有垂直管道/条的目标 C URL
【发布时间】:2013-06-06 13:32:35
【问题描述】:

我正在尝试在 URL 中使用垂直管道

输入字符串:http://testURL.com/Control?command=dispatch|HOME|ABC:User名称

-(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 看起来像编码字符串。

谢谢!

【问题讨论】:

标签: ios objective-c nsstring nsstringencoding


【解决方案1】:

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

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

【讨论】:

  • 我需要在 URL 中使用竖线 :)。不是 %7C。对不起,应该说清楚。
  • 那你就得找一些其他的类来处理 url 因为NSURL 不能...
  • 我使用了 ISOLatin 加密。将其更改为 NSUTF8StringEncoding。我的问题现在重复了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-15
  • 2010-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多