如何对字符串进行 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)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(24)
对于使用 UTF8Encode 将 NSString 编码为 cString 的 php 函数 urlencode,如 [NSString UTF8String] 不起作用。
这是我的自定义目标 c NSString+ASCIIencode 类别,适用于所有 ASCII 值 0..255
标头
实现
For the php function urlencode encoding a NSString to a cString with UTF8Encode, like [NSString UTF8String] was not working.
Here is my custom objective c NSString+ASCIIencode Category with works with all ASCII values 0..255
Header
Implementation
我遇到了类似的问题,将复杂的字符串作为 POST 参数传递。我的字符串可以包含亚洲字符、空格、引号和各种特殊字符。我最终找到的解决方案是将我的字符串转换为匹配的unicode系列,例如“Hu0040Hu0020Hu03f5....”,使用[NSString stringWithFormat:@"Hu%04x",[string characterAtIndex:i]]从每个字符串中获取Unicode原始字符串中的字符。在 Java 中也可以完成同样的操作。
该字符串可以作为 POST 参数安全地传递。
在服务器端(PHP),我将所有“H”更改为“\”,并将结果字符串传递给 json_decode。最后一步是在将字符串存储到 MySQL 之前转义单引号。
这样我就可以在我的服务器上存储任何 UTF8 字符串。
I faced a similar problem passing complex strings as a POST parameter. My strings can contain Asian characters, spaces, quotes and all sorts of special characters. The solution I eventually found was to convert my string into the matching series of unicodes, e.g. "Hu0040Hu0020Hu03f5...." using [NSString stringWithFormat:@"Hu%04x",[string characterAtIndex:i]] to get the Unicode from each character in the original string. The same can be done in Java.
This string can be safely passed as a POST parameter.
On the server side (PHP), I change all the "H" to "\" and I pass the resulting string to json_decode. Final step is to escape single quotes before storing the string into MySQL.
This way I can store any UTF8 string on my server.
这个对我有用。
我从此链接找到了上述函数: http://useyourloaf .com/blog/how-to-percent-encode-a-url-string/
您还可以通过 swift 扩展使用此函数。如果有任何问题,请告诉我。
This one is working for me.
I found the above function from this link: http://useyourloaf.com/blog/how-to-percent-encode-a-url-string/
You can also use this function with swift extension. Please let me know if there is any issue.
//这是未经测试的
//This is without test
对于个别www表单编码的查询参数,我在NSString上做了一个类别:
For individual www form-encoded query parameters, I made a category on NSString:
根据以下博客
according to the following blog
这么多答案但对我不起作用,所以我尝试了以下内容:
希望它会对某人有所帮助。谢谢
So many answers but didn't work for me, so I tried the following:
Hopefully it'll help someone. thanks
在 Swift 3 中,请尝试以下操作:
由于
stringByAddingPercentEscapesUsingEncoding
对非 URL 字符进行编码,但保留保留字符(例如!*'();:@& =+$,/?%#[]
), 您可以像下面的代码一样对 url 进行编码:In Swift 3, please try out below:
Since,
stringByAddingPercentEscapesUsingEncoding
encodes non URL characters but leaves the reserved characters (like!*'();:@&=+$,/?%#[]
), You can encode the url like the following code:在我的例子中,最后一个组件是阿拉伯字母,我在 Swift 2.2 中执行了以下操作:
用法:
In my case where the last component was Arabic letters I did the following in
Swift 2.2
:usage:
在快速3中:
In swift 3:
基于 chown 在此线程中的 objc 答案的 swift 代码。
swift code based on chown's objc answer in this thread.
使用 NSURLComponents 对 HTTP GET 参数进行编码:
http://www.ralfebert。 de/snippets/ios/encoding-nsurl-get-parameters/
Use NSURLComponents to encode HTTP GET parameters:
http://www.ralfebert.de/snippets/ios/encoding-nsurl-get-parameters/
Apple 在 10.11 发行说明中的建议是:
如果需要对整个 URL 字符串进行百分比编码,则可以使用此代码对旨在成为 URL 的 NSString 进行编码(在 urlStringToEncode 中):
Apple's advice, in the 10.11 release notes, is:
If you need to percent-encode an entire URL string, you can use this code to encode a NSString intended to be a URL (in urlStringToEncode):
在阅读了该主题的所有答案以及(错误)已接受的答案后,我想添加我的贡献。
如果目标是 iOS7+,并且在 2017 年应该会实现,因为 XCode 很难在 iOS8 下提供兼容性,最好的方法,线程安全,快速,AMD 将完全支持 UTF-8 来做到这一点是:
(目标 C 代码)
这将扩展 NSString,排除 RFC 禁止字符,支持 UTF-8 字符,并让您使用以下内容:
这将在调试控制台上打印:
... 注意还使用dispatch_once来避免多线程环境中的多次初始化。
After reading all the answers for this topic and the (wrong) accepted one, I want to add my contribution.
IF the target is iOS7+, and in 2017 it should since XCode makes really hard to deliver compatibility under iOS8, the best way, thread safe, fast, amd will full UTF-8 support to do this is:
(Objective C code)
This will extend NSString, will exclude RFC forbidden characters, support UTF-8 characters, and let you use things like:
That will print on your debug console:
... note also the use of dispatch_once to avoid multiple initializations in multithread environments.
这段代码帮助我编码特殊字符
This code helped me for encoding special characters
尝试将
stringByAddingPercentEncodingWithAllowedCharacters
方法与[NSCharacterSet URLUserAllowedCharacterSet]
一起使用,它将涵盖所有情况Objective C
swift
输出
测试%20%2F%20Test
Try to use
stringByAddingPercentEncodingWithAllowedCharacters
method with[NSCharacterSet URLUserAllowedCharacterSet]
it will cover all the casesObjective C
swift
Output
Test%20%2F%20Test
我选择使用接受的答案中给出的 CFURLCreateStringByAddingPercentEscapes 调用,但是在最新版本的 XCode(和 IOS)中,它导致了错误,因此使用了以下内容:
I opted to use the
CFURLCreateStringByAddingPercentEscapes
call as given by accepted answer, however in newest version of XCode (and IOS), it resulted in an error, so used the following instead:以下是 Swift 5.x 中的生产就绪灵活方法:
示例用法:
输出:
Here's a production-ready flexible approach in Swift 5.x:
Example usage:
Output:
iOS 7 更新
ios 7 update
Swift 2.0 示例(兼容 iOS 9)
Swift 2.0 Example (iOS 9 Compatiable)
这可能对 iOS 7+ 有帮助
,推荐的方法是:
您可以根据 URL 组件的要求选择允许的字符集。
This might be helpful
For iOS 7+, the recommended way is:
You can choose the allowed character set as per the requirement of the URL component.
自选择答案后已添加新的 API;您现在可以使用 NSURLUtilities。由于 URL 的不同部分允许使用不同的字符,因此请使用适用的字符集。以下示例进行编码以包含在查询字符串中:
要专门转换“&”,您需要将其从 url 查询集中删除或使用不同的集合,如“&”在 URL 查询中允许:
New APIs have been added since the answer was selected; You can now use NSURLUtilities. Since different parts of URLs allow different characters, use the applicable character set. The following example encodes for inclusion in the query string:
To specifically convert '&', you'll need to remove it from the url query set or use a different set, as '&' is allowed in a URL query:
不幸的是,
stringByAddingPercentEscapesUsingEncoding
并不总是 100% 有效。它对非 URL 字符进行编码,但保留保留字符(例如斜杠/
和与号&
)。显然这是苹果公司意识到的一个错误,但由于他们还没有修复它,我一直在使用这个类别来对字符串进行 url 编码:像这样使用:
这也有效:
一些好阅读有关该主题的内容:
Objective-c iPhone 百分比编码字符串?
Objective-C 和 Swift URL 编码
http://cybersam.com/programming/proper-url-percent-encoding-in-ios
https://devforums.apple.com/message/15674#15674
http://simonwoodside.com/weblog/2009/4/22/how_to_really_url_encode/
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:Used like this:
This also works:
Some good reading about the subject:
Objective-c iPhone percent encode a string?
Objective-C and Swift URL encoding
http://cybersam.com/programming/proper-url-percent-encoding-in-ios
https://devforums.apple.com/message/15674#15674
http://simonwoodside.com/weblog/2009/4/22/how_to_really_url_encode/