How do I URL encode a string(如何对字符串进行 URL 编码)
问题描述
我有一个带有空格和 &
字符的 URL 字符串 (NSString
).如何对整个字符串进行 url 编码(包括 &
和号字符和空格)?
I have a URL string (NSString
) with spaces and &
characters. How do I url encode the entire string (including the &
ampersand character and spaces)?
推荐答案
不幸的是,stringByAddingPercentEscapesUsingEncoding
并不总是 100% 有效.它对非 URL 字符进行编码,但保留保留字符(如斜线 /
和 & 符号 &
)单独.显然这是 Apple 知道的一个 错误,但由于他们还没有修复它,我一直在使用这个类别对字符串进行 url 编码:
Unfortunately, stringByAddingPercentEscapesUsingEncoding
doesn't always work 100%. It encodes non-URL characters but leaves the reserved characters (like slash /
and ampersand &
) alone. Apparently this is a bug that Apple is aware of, but since they have not fixed it yet, I have been using this category to url-encode a string:
@implementation NSString (NSString_Extended)
- (NSString *)urlencode {
NSMutableString *output = [NSMutableString string];
const unsigned char *source = (const unsigned char *)[self 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;
}
这样使用:
NSString *urlEncodedString = [@"SOME_URL_GOES_HERE" urlencode];
// Or, with an already existing string:
NSString *someUrlString = @"someURL";
NSString *encodedUrlStr = [someUrlString urlencode];
<小时>
这也有效:
This also works:
NSString *encodedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(
NULL,
(CFStringRef)unencodedString,
NULL,
(CFStringRef)@"!*'();:@&=+$,/?%#[]",
kCFStringEncodingUTF8 );
<小时>
一些关于这个主题的好读物:
Some good reading about the subject:
Objective-c iPhone 百分比编码字符串?
Objective-C 和 Swift URL 编码
http://cybersam.com/programming/proper-url-ios 中的百分比编码
https://devforums.apple.com/message/15674#15674http://simonwoodside.com/weblog/2009/4/22/how_to_really_url_encode/一个>
这篇关于如何对字符串进行 URL 编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何对字符串进行 URL 编码
基础教程推荐
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01