在swift中发送自定义HTTP标头

时间:2015-09-25 16:21:20

标签: json swift

我设法从我的服务器获取json但现在我想通过http头添加额外的安全性。这就是我的代码现在几乎看不出来的样子:

let urlPath = "http://www.xxxxxxxx.com"
        let url = NSURL(string: urlPath)
        let session = NSURLSession.sharedSession()
        let task = session.dataTaskWithURL(url!, completionHandler: { (data, response, error) -> Void in
            if ((error) != nil) {
                println("Error")
            } else {
                // process json
                let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary

                println(jsonResult["user"])
            }
        })

我想要添加到此请求的标头如下:

  • uid,包含整数值
  • 哈希,这是一个字符串

如果有帮助,我有另一个内置在Titanium框架中的应用程序,它使用以下语法:

xhr.setRequestHeader('uid', userid);
xhr.setRequestHeader('hash', hash);

所以,我基本上都在寻找一个Swift等价物。

2 个答案:

答案 0 :(得分:3)

You are using dataTaskWithURL while you should use dataTaskWithRequest, that takes NSMutableURLRequest object as an input. Using this object you can set HTTP headers, HTTPBody, or HTTPMethod

        let urlPath = "http://www.xxxxxxxx.com"
        let url = NSURL(string: urlPath)
        let session = NSURLSession.sharedSession()
        let request = NSMutableURLRequest(URL: url!)
        request.HTTPMethod = "GET" // make it post if you want
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")//This is just an example, put the Content-Type that suites you
        //request.addValue(userid, forHTTPHeaderField: "uid")
        //request.addValue(hash, forHTTPHeaderField: "hash")
        let task = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
          //do anything you want
        })
        task.resume()

答案 1 :(得分:1)

我建议您使用Alamofire进行联网 https://github.com/Alamofire/Alamofire

它是用Swift编写的,并且易于使用。看看那个页面。