Alamofire中的基本身份验证标头 [英] Basic auth header in Alamofire

查看:101
本文介绍了Alamofire中的基本身份验证标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个受保护的api,并且得到了它的用户名和密码.当我使用邮递员时,我选择基本身份验证"类型,并且在正文中有诸如用户登录信息之类的参数.效果很好.

I have a protected api and I got the username and password for it. When I use Postman I select the "Basic Auth" type and in the body I have the parameters such as the user login info. It works just fine.

但是我试图用Alamofire做同样的事情,但是我无法获得正确的JSON返回.这是我所做的:

However I'm trying to do the same thing with Alamofire but I can't get the right JSON return. Here is what I did :

  // user auth 
  let param = ["mobile":"3", "password":"100200"]
    let urlStr = "http://MyApi.com/api/login"
    let url = URL(string: urlStr)

    // api auth 
    let user = "apiUserName"
    let password = "ApiAuthPassword"


    var headers: HTTPHeaders = ["mobile":"001",
                                "password":"1111"]

    if let authorizationHeader = Request.authorizationHeader(user: user, password: password) {
        headers[authorizationHeader.key] = authorizationHeader.value
    }

    Alamofire.request(url!, headers: headers)
        .responseJSON { response in

            print(response.result.value)
            if let value: AnyObject = response.result.value as AnyObject? {
                //Handle the results as JSON
                print(value)
                let usertoken = JSON(value)

                print(usertoken)
            }



    }

这将返回nil.有人可以帮助我如何使用Alamofire执行Postman方法.谢谢!

This returns nil. Can someone help me how to do the Postman method with Alamofire. Thanks!

推荐答案

let user = "your username"

let password = "your password"

let credentialData = "\(user):\(password)".data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue))!

let base64Credentials = credentialData.base64EncodedString()


   let headers = [
            "Authorization": "Basic \(base64Credentials)", 
            "Accept": "application/json",
            "Content-Type": "application/json" ]

//put slash before \ (base64Credentials)

    Alamofire.request("place your url", method: .get, parameters: nil,encoding: URLEncoding.default, headers: headers) .responseJSON { response in
        switch response.result {
            case .success(_):   
               //your success code
            }      
            case .failure(_):
               //your failure code
            }
    }

这篇关于Alamofire中的基本身份验证标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆