2016-04-21 104 views
3

我必須發送一個https GET請求到我在Swift 1.2中開發的iPhone應用程序中的Web服務。在URL中編碼「&」問題

我想構建查詢字符串參數,但得到編碼之前發送到服務器。

當密碼包含'&'字符時,所有好但不工作。預計將'&'字符編碼爲'%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

想知道這樣做的正確方法。謝謝。

+4

除了這個問題,我絕不會在GET請求中發送明文密碼。 – vadian

+0

看看http://stackoverflow.com/a/31791424/1187415。 –

+1

你也應該考慮使用NSURLComponents&NSURLQueryItem。 – jtbandes

回答

3

您應該爲您的任務使用NSURLComponents

給定一個URL字符串,則創建一個url-組件:

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

給定查詢參數容器(可能是一個字典,或(字符串,字符串)元組的陣列?),創建NSURLQueryItems的陣列:

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

追加查詢組分到URL的組件:

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

print(urlComponents.string!) 

p rints:

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

我用這樣的實用方法URL編碼在GET-請求:

@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 
+1

雖然這是「嚴格」(所有保留的字符將被轉義),但它可能會導致URL值的問題。因此,'URLComponents'不會在查詢組件中爲「值」轉義下列字符:'/?@!$'()* +,;'這是安全的,因爲這些字符不是查詢組件中的分隔符。 – CouchDeveloper

0

如果需要編碼&字符,你可以使用以下命令:

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