在Swift中将cUrl命令转换为HTTP请求 [英] Convert cUrl command to HTTP Request in Swift

查看:262
本文介绍了在Swift中将cUrl命令转换为HTTP请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个用于检查域可用性的应用.现在,我正在使用goDaddy API;根据goDaddy的说法,检查URL可用性的方法是通过以下cURL命令:

I am building an app that checks domain availability. Right now, I am using the goDaddy API; according to goDaddy, the way to check URL availability is by the following cURL command:

curl -X GET -H "Authorization: sso-key {API_KEY}:{API_SECRET}" "https://api.godaddy.com/v1/domains/available?domain=example.guru"

现在,我正在尝试将该cURL命令转换为Swift.我正在使用Alamofire;但是,当我发出请求时,出现如下错误:

Right now, I am trying to translate that cURL command to Swift. I am using Alamofire; however, when I make a request, an error as the following shows up:

必须指定凭据

Credentials must be specified

我想知道如何解决这个问题.这是我当前的代码:

I was wondering how to solve this problem. Here is my current code:

class ViewController: UIViewController {

    let key = "KEYKEYKEY"
    let secret = "SECRETSECRET"

    var headers: HTTPHeaders = [:]

    override func viewDidLoad() {
        super.viewDidLoad()

        let credential = URLCredential(user: key, password: secret, persistence: .forSession)

        Alamofire.request("https://api.godaddy.com/v1/domains/available?domain=example.guru")
            .authenticate(usingCredential: credential)
            .responseJSON { response in
                debugPrint(response)
        }

        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

推荐答案

我知道这不是在使用Alamofire,但这是我将如何实现的方法.

I know that this is not using Alamofire but this is how I would achieve it.

import PlaygroundSupport
import Foundation
let key = "2s7Ymz8gu7_8XuTEeMFVmxJBLmyNNL4n8"
let secret = "8XuXAs8K37ejtYqvsEue2p"

let url = URL(string: "https://api.ote-godaddy.com/v1/domains/available?domain=example.guru&checkType=FULL")

var request = URLRequest(url: url!)

request.addValue("application/json", forHTTPHeaderField: "Accept")
request.addValue("sso-key \(key):\(secret)", forHTTPHeaderField: "Authorization")
let task = URLSession.shared.dataTask(with: request) { data, response, error in
    guard error == nil else {
        print(error!)
        return
    }
    guard let data = data else {
        print("Data is empty")
        return
    }

    let json = try! JSONSerialization.jsonObject(with: data, options: [])
    print(json)
}

task.resume()
PlaygroundPage.current.needsIndefiniteExecution = true

这篇关于在Swift中将cUrl命令转换为HTTP请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆