If you have tried to send any information using a GET web request, you would have come across an annoying problem. That annoying problem is making sure that the URL is correctly encoded.
At first glance it would seem that the Cocoa Frameworks do this for you, and you would be right …. well kind of.
The issue is that by default most of these methods leave characters such as & = ? within a URL, as they are strictly speaking valid. The problem is that these characters have special meanings in a GET request, and will more than likely make your request in valid.
Luckily there is a function in Core Foundation that helps:
1 2 3 4 5 6 7 |
|
What makes this function useful, is thelegalURLCharactersToBeEscapedparameter. This will escape legal characters such as & ? = if they are supplied. This allows you to escape parameters using the following code.
1 2 |
|
An example of when to use this, is Twitters Update status API. You can find that here http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-statuses%C2%A0update
To update your status to the following:
This is my status
You would need to post up the following URL:
http://twitter.com/statuses/update.xml?status=This%20is%20my%20status
As this is such a common problem of mine, I have created a category on NSURL. This allows you to pass in a base URL and a parameters dictionary.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
|
Using a parameters dictionary keeps the code nice and clean, but beware, to use the category method above you still have to make sure that your keys, and the base URL are correctly encoded (no spaces or invalid characters !!!!!).
As we now have a category method to do all the hard work for us, to create the Twitter URL you just need to do the following:
1 2 3 4 5 |
|
And thats it. Obviously this category can be used for things other than twitter ….. if you really want to.
本文深入解析了URL编码的原理与应用,通过Core Foundation提供的函数帮助正确处理URL参数,确保请求有效。以Twitter API为例,展示了如何利用自定义类别简化URL构建过程,避免常见的编码错误。
1万+

被折叠的 条评论
为什么被折叠?



