Swift: HTTP请求参数在header

Swift: HTTP request with parameters in header

我需要发送 HTTP 请求,我可以做到,但是我在 Backendless 中的 API 需要 HTTP 请求 Header 中的 application-id 和 secret-key。你能帮忙如何将它添加到我的代码中吗?谢谢

let urlString = "https://api.backendless.com/v1/data/Pub"
    let session = NSURLSession.sharedSession()
    let url = NSURL(string: urlString)!

    session.dataTaskWithURL(url){(data: NSData?,response: NSURLResponse?, error: NSError?) -> Void in

        if let responseData = data
        {
            do{
                let json = try NSJSONSerialization.JSONObjectWithData(responseData, options: NSJSONReadingOptions.AllowFragments)
                print(json)
            }catch{
                print("Could not serialize")
            }
        }

    }.resume()

Swift 5+、4.1+ 和 Swift 3

var request = URLRequest(url: url)
request.setValue("secret-keyValue", forHTTPHeaderField: "secret-key")

URLSession.shared.dataTask(with: request) { data, response, error in }

Swift 2.2

像这样将 NSURL 包装成 NSMutableRequest

let request = NSMutableURLRequest(URL: url)

然后使用此方法将 header 添加到您的 request object:

request.setValue("secret-keyValue", forHTTPHeaderField: "secret-key")

而不是使用 dataTaskWithURL: 使用 dataTaskWithRequest: 方法。

session.dataTaskWithRequest(request){
(data: NSData?,response: NSURLResponse?, error: NSError?) -> Void in }

我做到了。

let urlString = "https://api.backendless.com/v1/data/Pub"
        let session = NSURLSession.sharedSession()
        let url = NSURL(string: urlString)!
        let request = NSMutableURLRequest(URL: url)

        request.setValue("application-idValue", forKey: "application-id")
        request.setValue("secret-keyValue", forKey: "secret-key")

        session.dataTaskWithRequest(request){(data: NSData?,response: NSURLResponse?, error: NSError?) -> Void in

            if let responseData = data
            {
                do{
                    let json = try NSJSONSerialization.JSONObjectWithData(responseData, options: NSJSONReadingOptions.AllowFragments)
                    print(json)
                }catch{
                    print("Could not serialize")
                }
            }

        }.resume()
    }
 //MARK: GET Method
func GETDataFromServerUsingHeaderParameters(nameOfApi : NSString, parameters : NSString, withCurrentTask: RequestType, andDelegate : AnyObject) -> Void {
    if (currentReachabilityStatus != .notReachable){
        //print("Internet Connection Available!")
        currentTask = withCurrentTask
        let respectedURL = NSString(format: "%@%@", GlobalConstants.KBase_Url,nameOfApi,parameters)
        let myRequestUrl = (respectedURL.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed))!
        let url = NSURL(string: myRequestUrl as String)!
        let request = NSMutableURLRequest(url: url as URL)
        request.setValue("application-idValue", forKey: "application-id")
        request.setValue("secret-keyValue", forKey: "secret-key")
        request.httpMethod = "GET"
            let task = URLSession.shared.dataTask(with: request as URLRequest){ data,response,error in
            guard let data = data, error == nil else {
                self.showAlertMessage(title: "App Name", message: "Server not responding, please try later")
                self.delegate?.internetConnectionFailedIssue()
                return
            }
            if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
                self.delegate?.internetConnectionFailedIssue()
            }else{
                do {
                    self.responseDictionary = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! NSDictionary
                    self.delegate?.responseReceived()
                } catch {
                }
            }
        }
        task.resume()
    }else{
        self.showAlertMessage(title: "App Name", message: "No Internet Connection..")
    }
}