我正在尝试调用使用HTTP Basic Auth的本地Rest服务。
作为我请求的结果,我得到了以下内容:
找到:错误-未经授权
找到:原因-需要密码
下面是我的函数,它执行请求。
func connect(url: String) -> Bool {
let url: NSURL = NSURL(string: url);
let login:String = "admin";
let password:String = "test123";
var defaultCredentials: NSURLCredential = NSURLCredential(user: login, password: password, persistence: NSURLCredentialPersistence.ForSession);
let host: String = url.host;
let port: Int = url.port;
let prot: String = url.scheme;
println("set following vars \(host) + \(port) + \(prot)");
var protectionSpace: NSURLProtectionSpace = NSURLProtectionSpace(host: host,port: port,`protocol`: prot,realm: nil,authenticationMethod: NSURLAuthenticationMethodHTTPBasic);
var credentialStorage: NSURLCredentialStorage = NSURLCredentialStorage.sharedCredentialStorage();
credentialStorage.setCredential(defaultCredentials, forProtectionSpace: protectionSpace);
var sessionConfiguration: NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration();
sessionConfiguration.URLCredentialStorage = credentialStorage;
let session: NSURLSession = NSURLSession(configuration: sessionConfiguration); //NSURLSession.sharedSession()
//NSURLSession.sessionWithConfiguration(sessionConfiguration);
let task = session.dataTaskWithURL(url, completionHandler: {data, response, error -> Void in
println("Task completed")
if((error) != nil) {
// If there is an error in the web request, print it to the console
println(error.localizedDescription)
}
var err: NSError?
var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSDictionary
if(err != nil) {
// If there is an error parsing JSON, print it to the console
println("JSON Error \(err!.localizedDescription)")
}
self.delegate.didReceiveAPIResults(jsonResult);
})
task.resume()
return true
}有谁能给我个提示吗?
发布于 2014-10-16 04:47:59
这是最基本的方法(从这里开始:https://stackoverflow.com/a/24380884),但它是有效的:
// set up the base64-encoded credentials
let username = "user"
let password = "pass"
let loginString = NSString(format: "%@:%@", username, password)
let loginData: NSData = loginString.dataUsingEncoding(NSUTF8StringEncoding)
let base64LoginString = loginData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.fromMask(0))
// create the request
let url = NSURL(string: "http://www.example.com/")
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")
// fire off the request
// make sure your class conforms to NSURLConnectionDelegate
let urlConnection = NSURLConnection(request: request, delegate: self)如果您收到身份验证质询,下面将介绍一种更好的方法:
https://stackoverflow.com/questions/25371404
复制相似问题