编码"&"在URL中

时间:2016-04-21 15:15:51

标签: ios swift nsurl

我必须向我的iPhone应用程序中的Web服务发送https GET请求,该应用程序是在Swift 1.2中开发的。

我正在尝试构造查询字符串参数,但在发送到服务器之前必须对它们进行编码。

密码包含'&'字符内。期待编码'&'字符到'%26'但不工作......

刚刚进行了一次测试'%'。按预期工作'%'提供'%25'。但不能转换'&'签....

尝试以下方式:

var testPassword1: String = "mypassword&1"

var testPassword2: String = "mypassword%1"


// Try to encode 'testPassword1'
testPassword1.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)! 
testPassword1.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())!


// Try to encode 'testPassword2'
testPassword2.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
testPassword2.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())!

我已完成上述测试,以下是回复

enter image description here

想知道这样做的正确方法。感谢。

3 个答案:

答案 0 :(得分:3)

您应该使用NSURLComponents完成任务。

给定一个URL字符串,创建一个url-components:

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

给定一个查询参数容器(可能是一个字典,或一个(String,String?)元组的数组),创建一个NSURLQueryItems数组:

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

将查询组件附加到url-components:

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

print(urlComponents.string!)

打印:

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

答案 1 :(得分:0)

我使用这样的实用工具方法在GET请求中对进行URL编码:

@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

答案 2 :(得分:0)

如果您需要编码&字符,您可以使用以下内容:

var testPassword1: String = "mypassword&1"
testPassword1.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
testPassword1.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet(charactersInString: "&").invertedSet)!