尝试连接到我的服务器时使用 Alamofire 和 swift 出现 401 错误

401 error using Alamofire and swift when trying to connect to my server

好的,所以我正在尝试将 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";

非常感谢您对此的任何帮助

大家好,经过更多的努力,我开始工作了。我摆脱了上面的所有东西并变得简单。它效果更好,更容易做到

这是供任何人使用的工作代码

    Alamofire.request(.GET, promoUrl, parameters: [myUserName:myPassword])
        .authenticate(user: myUserName, password: myPassword)
        .response {(request, response, data, error) in
            print(response)


    }

关键区别在于此

parameters: [myUserName:myPassword]

这会将我的密码和用户名载入 url。这可能不是最好的方法,但它现在可以满足我的需要