如何在下面的代码中添加 headers 和参数

How to add headers and parameters in my Code Below

我有一个代码可以从 URL 中获取内容,但是我如何为下面的代码添加 headers 和参数。

let url = NSURL(string: catURL)
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
let task = session.dataTask(with: url as! URL) {
        ( data, response, error) in
        if let taskHeader = response as? HTTPURLResponse {
          print(taskHeader.statusCode)
        }
        if error != nil {
            print("There is an error!!!")
            print(error)
        } else {
            if let content = data {
                do {
                    let array = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
                     let dictionary = try JSONSerialization.jsonObject(with: content) as! [String:Any]
                    if let items = dictionary["course"] as? [[String:Any]] {
                        for item in items {
                           if let ids = item["name"] {                                    
                               print("iDS = \(ids)")
                            }

您应该使用 headers 创建 URLRequest 并在此请求中使用 dataTask

您可以这样设置参数:

url.queryItems = [
    URLQueryItem(name: "parameterName", value: "parameterValue")
]

可以设置httpMethod

let request = URLRequest(url: url)
request.httpMethod = "POST" // "POST", "GET", "PUT", "DELETE"

添加headers

request.setValue("application/json", forHTTPHeaderField: "Content-Type")

您可以设置jsonData并在请求中使用此数据

let json = [
    "key1": "value1",
    "key2": "value2"
]

词典到JSON:

let jsonData = try! JSONSerialization.data(withJSONObject: json, options: [])

用法

let task = session.uploadTask(with: request, from: jsonData) { data, response, error in
    // Do something...
}
task.resume()

奖金

/// Print response data
if let data = data, let dataString = String(data: data, encoding: .utf8) {
    print(dataString)
}

/// Print status code
if let httpResponse = response as? HTTPURLResponse {
    print(httpResponse.statusCode)
}

示例

let url = URLComponents(string: catURL)
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)

url.queryItems = [
    URLQueryItem(name: "parameterName", value: "parameterValue")
]

let request = URLRequest(url: url)
request.allHTTPHeaderFields = ["application/json": "Content-Type"]

let task = session.dataTask(with: request) { ( data, response, error) in
    if let taskHeader = response as? HTTPURLResponse {
        print(taskHeader.statusCode)
    }

    if error != nil {
        print("There is an error!!!")
        print(error)
    } else {
        if let content = data {
            do {
                let array = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
                 let dictionary = try JSONSerialization.jsonObject(with: content) as! [String:Any]
                if let items = dictionary["course"] as? [[String:Any]] {
                    for item in items {
                       if let ids = item["name"] {                                    
                           print("iDS = \(ids)")
                        }