本文介绍了快速发送自定义HTTP标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我设法从服务器中获取json,但现在我想通过http标头添加额外的安全性.这是我的代码现在几乎没有的样子:

I managed to fetch json from my server but now I want to add extra security by way of http headers. This is how my code barely looks like for now:

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

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

The headers that I want to add to this request are the following:

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

如果有帮助,我还有另一个使用此语法的Titanium框架构建的应用程序:

If it helps, I have another app built in Titanium framework which uses this syntax:

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

因此,我基本上是在寻找Swift的等效产品.

So, am basically looking for a Swift equivalent.

推荐答案

您正在使用dataTaskWithURL,而您应该使用dataTaskWithRequest,它将NSMutableURLRequest对象作为输入.使用此对象,您可以设置HTTP标头,HTTPBody或HTTPMethod

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()

这篇关于快速发送自定义HTTP标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 11:17