在swift中发送自定义HTTP头
我设法从我的服务器获取json,但现在我想通过http头添加额外的安全性。这就是我的代码几乎看起来像现在:在swift中发送自定义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,它拥有一个整数值
- 哈希,这是一个字符串
如果有帮助,我有建于钛框架另一个应用程序使用这个语法:
xhr.setRequestHeader('uid', userid);
xhr.setRequestHeader('hash', hash);
所以,基本上是寻找一个Swift等价物。
我建议你使用Alamofire联网 https://github.com/Alamofire/Alamofire
这是写在雨燕是每一个易于使用。看看那个页面。
Swift已经配备了一套强大的网络API。 –
其实我没看到你评论的原因。从来没有说过它更强大,我只是觉得它更容易使用,所以我建议使用它。 – r4id4
我的评论是什么原因? bty这不是我的降低,我正在检查图书馆,这是很好的,但我总是喜欢与本地 –
您正在使用dataTaskWithURL
,而您应该使用dataTaskWithRequest
,这需要NSMutableURLRequest
对象作为输入。使用这种对象可以设置的HTTP标头,HTTPBody,或列举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()
可能重复的[NSURLSessionConfiguration HTTPAdditionalHeaders未设置(http://stackoverflow.com/questions/24751768/nsurlsessionconfiguration-httpadditionalheaders-not-set) – Abizern
@Abizern这个问题怎么能成为这个问题的重复?那一个是针对objective-c的不是? –
@WilliamKinaan答案在Swift中,并回答了这个问题。 – Abizern