问题
Any idea why NSURLSession
returns this response:
The authorization type you provided is not supported. Only Basic and OAuth are supported
let username = "8r6nibK8Pe28WFhjTX1gGb1Rhhhc7xM02v7XKRPedL4"
let password = "8r6nibK8Pe28WFhjTX1gGb1Rhhhc7xM02v7XKRPedL4"
let loginString = NSString(format: "%@:%@", username, password)
let loginData: NSData = loginString.dataUsingEncoding(NSUTF8StringEncoding)!
let base64LoginString = loginData.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let authString = "Basic \(base64LoginString)"
config.HTTPAdditionalHeaders = ["Authorization" : authString]
let url = NSURL(string: "https://api.datamarket.azure.com/Bing/Search/Image?$format=json&Query='Rambo'+'Oscar'")
let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"
let a = NSURLSession(configuration: config).dataTaskWithRequest(request, completionHandler: {data, urlResponse, error in
if data != nil {
let str = NSString(data: data!, encoding: NSUTF8StringEncoding)
print(str)
} else {
_ = 7
}
})
a.resume()
Browser returns different response with meaningful image information. And I am using basic authentication to send request.
回答1:
The problem may probably the option: .Encoding64CharacterLineLength
. try:
let base64LoginString = loginData.base64EncodedStringWithOptions([])
To investigate use Charles Proxy to see the difference in the requests. – zaph 10 mins ago
来源:https://stackoverflow.com/questions/32907981/nsurlsession-returns-different-response-than-browser-would-why