将CURL转换为URLRequest [英] Convert CURL to URLRequest

查看:140
本文介绍了将CURL转换为URLRequest的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将以下卷曲请求转换为Swagger给我的URLRequest:

I’m trying to converting the the following curl request Swagger gives me to URLRequest:

curl -X GET --header 'Accept: application/json' 
--header 'Authorization: key ttn-account-v2.<app-key>'
 'https://<app-id>.data.thethingsnetwork.org/api/v2/query'

URL和标头设置正确.我仍然收到响应:401-未经授权.

URL and Headers are set correctly. Still I get the response: 401 - Not authorized.

let key = "ttn-account-v2.<app-key>"

let url = URL(string: "https://<app-id>.data.thethingsnetwork.org/api/v2/query")

var request = URLRequest(url: url!)

request.httpMethod = "GET"
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.addValue("key \(key)", forHTTPHeaderField: "Authorization")

let task = URLSession.shared.dataTask(with: url!) { 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()

我想念什么吗?

推荐答案

出问题的是,您创建了一个完美的请求,然后通过仅使用url和 dataTask 跳过了所有请求不是请求.这样, HTTPHeaders 不会随请求一起发送,因此未经授权.只需将任务创建行更改为此:

What is going wrong is that you create a perfect request but then skip it all together by doing a dataTask with just the url and not the request. This way the HTTPHeaders aren't send with the request, thus it is not authorised. Just change the task creation line to this:

let task = URLSession.shared.dataTask(with: req) { data, response, error in 
    ...
}

这篇关于将CURL转换为URLRequest的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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