NSURLSession会返回与浏览器不同的响应,为什么?

时间:2015-10-02 13:12:22

标签: ios ios9 nsurlsession

知道为什么NSURLSession会返回此回复:

  

不支持您提供的授权类型。只有基本和   支持OAuth

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()

浏览器返回具有有意义图像信息的不同响应。我正在使用基本身份验证来发送请求。

1 个答案:

答案 0 :(得分:2)

问题可能是选项:.Encoding64CharacterLineLength。尝试:

let base64LoginString = loginData.base64EncodedStringWithOptions([])

调查使用Charles Proxy以查看请求中的差异。 - zaph 10分钟前