gpt4 book ai didi

json - Swift 中使用 Campaign Monitor 进行 HTTP 身份验证请求

转载 作者:行者123 更新时间:2023-11-30 11:05:41 26 4
gpt4 key购买 nike

当用户在我的应用程序中注册时,我尝试将用户数据发布到 Campaign Monitor。任何人都可以帮我将授权添加到请求中。我目前收到此错误:

Optional("{\"Code\":50,\"Message\":\"Must supply a valid HTTP Basic Authorization header\"}")

我的代码:

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)
}

//然后可以设置 session

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

最佳答案

在这一行中:

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

这是不正确的,即使他们告诉了你原因。您需要一个基本身份验证 header

For POST requests in Swift, generally you have to set the following:

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

祝你好运

关于json - Swift 中使用 Campaign Monitor 进行 HTTP 身份验证请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52763503/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com