iOS NSMutableURLRequest Authorization Header

时间:2015-07-31 19:51:20

标签: ios ruby swift alamofire

I am having trouble accessing an API call and I think it has something to do with the authorization header. I am using AlamoFire and printing out the token so I know it is valid.

var URLRequest: NSURLRequest {
    let URL = NSURL(string: Router.baseURLString + path)!
    let mutableURLRequest = NSMutableURLRequest(URL: URL)
    mutableURLRequest.HTTPMethod = method.rawValue

    println(Router.OAuthToken)
    if let token = Router.OAuthToken {
        mutableURLRequest.setValue("Token token=\(token)", forHTTPHeaderField: "Authorization")
    }

    println(mutableURLRequest)

    switch self {
    default:
        return mutableURLRequest
    }
}

This is what the documentation says and it works right in the terminal with the auth token:

curl -H "Authorization: Token token=<ACCESS_TOKEN>" http://10x.xx.xx.xxx/api/v1/users/feed

Here is the error I'm receiving:

Optional(Error Domain=com.alamofire.error Code=-1 "The operation couldn’t be completed. (com.alamofire.error error -1.)")

import Foundation
import Alamofire
import CoreData

enum Router: URLRequestConvertible {
    static let baseURLString = "http://104.131.81.230/api/v1"
    static var OAuthToken: String?

    case UserProfile
    case FacebookAuth(String)
    case Classes

    var method: Alamofire.Method {
        switch self {
        case .UserProfile:
            return .POST
        case .FacebookAuth:
            return .POST
        case .Classes:
            return .POST
        }
    }

    var path: String {
        switch self {
        case UserProfile:
            return "/users/me"
        case FacebookAuth(let fbAuthToken):
            return "/authentications/?access_token=\(fbAuthToken)"
        case Classes:
            return "/classes/"
        }
    }

    var URLRequest: NSURLRequest {
        let URL = NSURL(string: Router.baseURLString + path)!
        let mutableURLRequest = NSMutableURLRequest(URL: URL)
        mutableURLRequest.HTTPMethod = method.rawValue

        println(Router.OAuthToken)
        if let token = Router.OAuthToken {
            println("got token")

            mutableURLRequest.setValue("Token token=<\(token)>", forHTTPHeaderField: "Authorization")
        }

        println(mutableURLRequest)

        switch self {
        default:
            return mutableURLRequest
        }
    }
}

Alamofire.request(Router.Classes).validate(statusCode: 200 ..< 300).responseJSON(completionHandler: { (request, response, JSON, error) in
        println(JSON)
        println(error)
        if let _json = JSON as? [Dictionary<String, AnyObject>] {
            println(_json)
            for json in _json {

            }
        }
    })

This is the Alamofire request being print out using debugPrintln(), I am getting a 404 error.

    $ curl -i \
        -X POST \
        -H "Authorization: Token token=f804414300d84a929b7cec4148fcfd7f" \
        -H "Accept-Language: en;q=1.0,fr;q=0.9,de;q=0.8,zh-Hans;q=0.7,zh-Hant;q=0.6,ja;q=0.5" \
        -H "Accept-Encoding: gzip;q=1.0,compress;q=0.5" \
        -H "User-Agent: xxx/com.xxx.xxxx (1; OS Version 8.4 (Build 12H141))" \
"http://10X.XXX.XX.XX/api/v1/classes/"

1 个答案:

答案 0 :(得分:0)

您收到错误是因为您很可能从服务器获得401响应,导致状态代码验证失败。我建议打印出你收到的response。很可能会显示401状态代码的身份验证问题。

这里有用的是让您使用Alamofire中的debugPrintln(request)功能来调试正在生成的cURL命令。我猜想授权标题的组合方式与您预期的方式不同。您应该尝试以下方法:

let request = Alamofire.request(Router.Classes)
    .responseJSON { request, response, json, error in
        println(request)
        println(response)
        println(json)
        println(error)
    }

debugPrintln(request)

这可以帮助您调试为什么您最有可能获得401响应。如果您可以尝试一下并回复我,我会相应地更新我的答案。

祝你好运!