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

时间:2019-07-11 10:19:35

标签: swift http-headers nsurlsession

我有一个代码可以从URL提取内容,但是如何在下面为该代码添加标题和参数。

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)")
                            }

1 个答案:

答案 0 :(得分:4)

您应该使用标题创建URLRequest,并在此请求中使用dataTask

您可以设置以下参数:

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

您可以设置httpMethod

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

添加标题

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)")
                        }