0

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

Optional("{\"Code\":50,\"Message\":\"必须提供有效的 HTTP 基本授权标头\"}")

我的代码:

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()
4

1 回答 1

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?

祝你好运

于 2018-10-11T15:16:58.683 回答