Swift:Mailgun 401 响应代码--未提供有效的 API 密钥

问题描述

所以我有我的发送电子邮件功能,如下所示:

func email() {
    let session = URLSession.shared
    let request = NSMutableuRLRequest(url: NSURL(string: "https://api.mailgun.net/v3/sandBox################################/messages")! as URL)

    request.httpMethod = "POST"
    let credentials = "api:key-################################-########-########"
    request.setValue("Basic \(credentials.toBase64())",forHTTPHeaderField: "Authorization")

    let data = "from: Swift Email <(test@test.com)>&to: [myemail@gmail.com,(myemail@gmail.com)]&subject:Hello&text:Testing_some_Mailgun_awesomness"
    request.httpBody = data.data(using: String.Encoding.ascii)

    let task = session.dataTask(with: request as URLRequest,completionHandler: {(data,response,error) in
        if let error = error {
            print(error)
        }
        if let response = response {
            print("url = \(response.url!)")
            print("response = \(response)")
            let httpResponse = response as! HTTPURLResponse
            print("response code = \(httpResponse.statusCode)")
        }
    })
    task.resume()
}

所以我猜要么是我的 API 密钥错误,要么是我的请求 URL 错误。为了找到我的请求 URL,我转到 https://app.mailgun.com/app/dashboard,然后向下滚动到发送域部分并复制它。为了获取我的 API 密钥,我去了 https://app.mailgun.com/app/account/security/api_keys 并复制了私有 API 密钥。我真的不知道为什么我会收到这个无效的代码——如果你弄清楚了,提前谢谢你!

旁注:不确定数据常量是否设置正确(就缺少或有太多括号而言),所以如果你也能检查一下,那就太棒了。

解决方法

我有一个名为“paw”的软件,它有助于为 Xcode、curl、php 等形成 REST API 调用。

不知道能不能帮到你

class MyRequestController {
    func sendRequest(somevar: String,completion: @escaping (Books) -> Void) {
        /* Configure session,choose between:
           * defaultSessionConfiguration
           * ephemeralSessionConfiguration
           * backgroundSessionConfigurationWithIdentifier:
         And set session-wide properties,such as: HTTPAdditionalHeaders,HTTPCookieAcceptPolicy,requestCachePolicy or timeoutIntervalForRequest.
         */
        let sessionConfig = URLSessionConfiguration.default

        /* Create session,and optionally set a URLSessionDelegate. */
        let session = URLSession(configuration: sessionConfig,delegate: nil,delegateQueue: nil)

        /* Create the Request:
            (POST https://api.mailgun.net/v3/YOUR_DOMAIN_NAME/messages)
         */

        guard var URL = URL(string: "https://api.mailgun.net/v3/YOUR_DOMAIN_NAME/messages") else {return}
        var request = URLRequest(url: URL)
        request.httpMethod = "POST"

        // Headers

        request.addValue("Basic YXBpOllPVVJfQVBJX0tFWQ==",forHTTPHeaderField: "Authorization")
        request.addValue("multipart/form-data; charset=utf-8; boundary=__X_PAW_BOUNDARY__",forHTTPHeaderField: "Content-Type")

        // Body

        let bodyString = "--__X_PAW_BOUNDARY__\r\nContent-Disposition: form-data; name=\"from\"\r\n\r\n'Excited User <mailgun@YOUR_DOMAIN_NAME>'\r\n--__X_PAW_BOUNDARY__\r\nContent-Disposition: form-data; name=\"to\"\r\n\r\nYOU@YOUR_DOMAIN_NAME\r\n--__X_PAW_BOUNDARY__\r\nContent-Disposition: form-data; name=\"to\"\r\n\r\nbar@example.com\r\n--__X_PAW_BOUNDARY__\r\nContent-Disposition: form-data; name=\"subject\"\r\n\r\n'Hello'\r\n--__X_PAW_BOUNDARY__\r\nContent-Disposition: form-data; name=\"text\"\r\n\r\n'Testing some Mailgun awesomeness!'\r\n--__X_PAW_BOUNDARY__--\r\n"
        request.httpBody = bodyString.data(using: .utf8,allowLossyConversion: true)

        /* Start a new Task */
        let task = session.dataTask(with: request,completionHandler: { (data: Data?,response: URLResponse?,error: Error?) -> Void in
            if (error == nil) {
                // Success
                let statusCode = (response as! HTTPURLResponse).statusCode
                print("URL Session Task Succeeded: HTTP \(statusCode)")
            }
            else {
                // Failure
                print("URL Session Task Failed: %@",error!.localizedDescription);
            }
        })
        task.resume()
        session.finishTasksAndInvalidate()
    }
}

**** 和你调用这个函数有点像这样

MyRequestController().sendRequest(somevar: "something")

查看https://www.youtube.com/watch?v=44APgBnapag了解更多详情 本教程展示了如何使用 Xcode 进行 REST API 调用,此示例扫描条形码,通过调用 API 的函数发送扫描的代码并返回信息...