好的,所以我试图将json文件作为字符串下载并将其解析出来。但我必须先从我的网页下载它。此网页需要用户名和密码才能访问它。这一直给我一个401错误,所以它没有发送用户名或密码。如何在请求中添加用户名和密码?
print("Downloading the json file")
let plainString = "\(myUserName):\(myPassword)" as NSString
let plainData = plainString.dataUsingEncoding(NSUTF8StringEncoding)
let base64String = plainData?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
Alamofire.Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders = ["Authorization": "Basic " + base64String!]
Alamofire.request(.GET, promoUrl)
.response {(request, response, _, error) in
print(response)
}
这是它的结果
Optional(<NSHTTPURLResponse: 0x7fe103818790> { URL: http://xxxapi/1.0/promotions } { status code: 401, headers {
"Cache-Control" = "no-cache, no-store, max-age=0, must-revalidate";
Connection = "keep-alive";
"Content-Length" = 186;
"Content-Type" = "application/json;charset=UTF-8";
Date = "Thu, 12 May 2016 01:36:33 GMT";
Expires = 0;
Pragma = "no-cache";
Server = "Apache-Coyote/1.1";
"Www-Authenticate" = "Basic realm=\"Realm\"";
"X-Content-Type-Options" = nosniff;
"X-Frame-Options" = DENY;
"X-XSS-Protection" = "1; mode=block";
非常感谢您对此的任何帮助
答案 0 :(得分:0)
大家好,经过努力之后,我得到了它的工作。我摆脱了顶部的所有东西,变得简单。它工作得更好,更容易做到
这是任何想要它的人的工作代码
Alamofire.request(.GET, promoUrl, parameters: [myUserName:myPassword])
.authenticate(user: myUserName, password: myPassword)
.response {(request, response, data, error) in
print(response)
}
关键区别在于
parameters: [myUserName:myPassword]
这会将我的密码和用户名加载到网址中。它可能不是最好的方法,但它现在适合我的需要