代码之家  ›  专栏  ›  技术社区  ›  richc

在Swift中使用活动监视器的HTTP身份验证请求

  •  0
  • richc  · 技术社区  · 6 年前

    可选(“{\”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 回复  |  直到 6 年前
        1
  •  0
  •   excitedmicrobe    6 年前

    在此行中:

    // 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?