Swift中Campaign Monitor的HTTP身份验证请求

时间:2018-10-11 15:11:41

标签: json swift http campaign-monitor

当他们在我的应用程序中注册时,我试图将用户数据发布到Campaign Monitor。谁能帮助我将授权添加到请求中。我目前收到此错误:

  

Optional(“ {\” Code \“:50,\” Message \“:\”必须提供有效的HTTP Basic   授权标头\“}”)

我的代码:

let parameters = [  "FirstName1": "test",
                    "SecondName": "test",
                    "email": "test@test.com"
                    ]

let clientID = "52bb93ac4d9a3f261abcda0123456789"
let url = URL(string: "https://api.createsend.com/api/v3.2/clients.json")!
var request = URLRequest(url: url)
request.httpMethod = "Post"

do {
    request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
} catch let error {
    print(error.localizedDescription)
}

// add the API Key to the request / security
request.setValue(clientID, forHTTPHeaderField: "username") // IS THIS RIGHT??

//这是我建立正确授权的方式

let APIKey = "0069b38c27b3e44de0234567891011"
let listID = "5e61fde130969d561dc0234567891011"

    let url = URL(string: "https://api.createsend.com/api/v3.2/subscribers/\(listID).json")!
    var request = URLRequest(url: url)
    request.httpMethod = "POST"

    // add the API Key to the request / security
    let loginString = "\(APIKey)"
    let loginData = loginString.data(using: String.Encoding.utf8)
    let base64LoginString = loginData!.base64EncodedString()
    request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")

do {
        request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
    } catch let error {
        print(error.localizedDescription)
    }

//然后可以设置会话

let session = URLSession(configuration: .default)
let task = session.dataTask(with: request) {

    (data, response, error) in

    if error != nil {
        print("Error is: \(String(describing: error))")
    }

    if let response = response {
        let nsHTTPResponse = response as! HTTPURLResponse
        let statusCode = nsHTTPResponse.statusCode
        print("status code = \(statusCode)")
    }

    if let data = data {
        let postResponse = String(data: data, encoding: .utf8)
        print("responseString = \(String(describing: postResponse))")
    }

}
task.resume()

1 个答案:

答案 0 :(得分:0)

在此行:

// add the API Key to the request / security
request.setValue(clientID, forHTTPHeaderField: "username") // IS THIS RIGHT??

这是不正确的,即使他们告诉了你原因。您需要一个Basic Auth Header

  

对于Swift中的POST请求,通常必须设置以下内容:

request.setValue("Basic " + clientID, forHTTPHeaderField: "Authorization") // is clientID your access token?

祝你好运