Issue with encoding “&” in URLs

跟風遠走 提交于 2019-12-01 21:01:11

You should use NSURLComponents for your task.

Given a URL string, create a url-components:

let urlString = "http://example.com"
let urlComponents = NSURLComponents(string: urlString)!

Given a query parameter container (possibly a dictionary, or an array of (String, String?) tuple), create an array of NSURLQueryItems:

let queryParameters: [String: String?] = ["param": "az09-._~!$&'()*+,;=:@/?", "reserved": ":/?#[]@!$&'()*+,;="]
var queryItems = queryParameters.map { NSURLQueryItem(name: $0.0, value: $0.1) }

Append the query-component to the url-components:

urlComponents.queryItems = queryItems.count > 0 ? queryItems : nil

print(urlComponents.string!)

prints:

http://example.com?reserved=:/?%23%5B%5D@!$%26'()*+,;%3D&param=az09-._~!$%26'()*+,;%3D:@/?

I used such an utility method to URL-encode values in GET-requests:

@interface NSString (Ext)

@property (nonatomic, readonly) NSString *urlEncoded;

@end

@implementation NSString (Ext)

- (NSString *)urlEncoded {
    NSMutableCharacterSet *const allowedCharacterSet = [NSCharacterSet URLQueryAllowedCharacterSet].mutableCopy;
    // See https://en.wikipedia.org/wiki/Percent-encoding
    [allowedCharacterSet removeCharactersInString:@"!*'();:@&=+$,/?#[]"]; // RFC 3986 section 2.2 Reserved Characters (January 2005)
    NSString *const urlEncoded = [self stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacterSet];
    return urlEncoded;
}

@end

If you need to encode the & character, you can use the following:

var testPassword1: String = "mypassword&1"
testPassword1.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
testPassword1.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet(charactersInString: "&").invertedSet)!
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!