Swift 2如何向POST请求添加授权标头

时间:2016-05-27 03:14:41

标签: post swift2 authorization

在发出特定的POST请求时,Firefox(FF)dev工具会显示一个req。名为“Authorization”的标题,其值为“Bearer X”,其中X是登录时收到的访问令牌。当我在FF中编辑此请求并删除“授权”行时,我收到400错误。当我把它放回去时,200并且一切都很顺利。但是,我还没有想出如何在不获取400的情况下以编程方式设置此请求标头。

此外,FF工具作为{“source”:“desktop - profile 2015”}的“请求主体”。我假设这是JSON。我试过用几种方式发布这个(见代码),但没有成功。

// the following fields are set in the object "Request"'s initialization
let accessToken = "1,2,3456789012,3x4f560fa7a89e01a2;33ab4b4e5e67e8e9b9f0e1a23db45678f9a9a0ff" // replaced some characters for this StackOF posting
let authorization = "Bearer \(accessToken)"
let method = "POST"
let userID = "1234567"
let URL = NSURL(string: "https://www.somesite.com/apitun/profile/\(userID)hide")

// tried setting params to all of the following 4:
let params = ""
let params = "&_json={}"
let params = "&_json={\"source\":\"desktop profile - 2015\"}
let params = "&_json=%7B%22source%22%3A%22desktop%2Dprofile%202015%22%7D"

func execute() {
    let session = NSURLSession.sharedSession()
    let request = NSMutableURLRequest(URL: URL)
    if authorization != "" {
        request.addValue(authorization, forHTTPHeaderField: "Authorization")
    }

    request.HTTPMethod = self.method
    request.HTTPBody = self.params.dataUsingEncoding(NSUTF8StringEncoding)
    self.task = session.dataTaskWithRequest(request) {
        (data, response, error) in
        NSHTTPCookieStorage.sharedHTTPCookieStorage().setCookies(self.cookies, forURL: self.URL, mainDocumentURL: nil)
        if error == nil {
            do {
                self.responseHeaders = response as! NSHTTPURLResponse
                self.cookies = NSHTTPCookieStorage.sharedHTTPCookieStorage().cookiesForURL(self.URL)!
                self.statusCode = self.responseHeaders.statusCode

                switch self.statusCode {

                case 200:
                    self.contentsOfURL = try NSString(contentsOfURL: self.URL, encoding: NSUTF8StringEncoding)
                case 400:
                    print("400: page not found")

                case 404:
                    print("404: page not found")

                case 407:
                    print("407: failed authenticate proxy credentials")

                default:
                    print("unable to get statusCode")

                }
            } catch {

            }
            self.isRequesting = false
        } else {
            print(error)
        }
    }
    self.task.resume()
}   

1 个答案:

答案 0 :(得分:12)

let request = NSMutableURLRequest(URL: NSURL(string: fullURL)!)

let accessToken = "your access token"
request.setValue("Bearer \(accessToken)", forHTTPHeaderField: "Authorization")