NSURLSession returns different response than browser would, why?

妖精的绣舞 提交于 2020-01-14 14:33:48

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!