我尝试在swift 2.0中提出一些网址请求:
func chackAccess(username: String!, password: String!) {
let request = NSMutableURLRequest(URL: NSURL(string: url)!)
request.HTTPMethod = "POST"
let postString = "username=\(username)&password=\(password)"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil {
print("error=\(error)")
return
}
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString!)")
if responseString != "null" {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.performSegueWithIdentifier("login", sender: self)
})
} else {
print("shake")
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.wrongPassword()
})
}
}
task.resume()
}
只有当我拥有像a-z 0-9这样的简单密码时,一切都很有效(但问题是char +。
问题出在哪里?
答案 0 :(得分:2)
某些字符在网址字符串中具有特殊含义:&
分隔参数,+
代表空格等。
尝试逃避它的百分比:
let charset = NSMutableCharacterSet.alphanumericCharacterSet()
let username = "auser"
let password = "abc(+.,?/[])123".stringByAddingPercentEncodingWithAllowedCharacters(charset)!
let postString = "username=\(username)&password=\(password)"
// username=auser&password=abc%28%2B%2E%2C%3F%2F%5B%5D%29123
stringByAddingPercentEncodingWithAllowedCharacters(charset)
转义不在charset
中的所有字符。例如:+ --> %2B