简体   繁体   English

如何使用Alamofire 4.0发出NTML请求?

[英]How to make a NTML request with Alamofire 4.0?

These are request headers: 这些是请求标头:

    let headers: HTTPHeaders = [
        "Accept": "application/json",
        "username": "someUserName",
        "password": "aPasswordForSomeUserName"
    ]

When making a request with below code it's giving me "Garbage at the end". 当使用以下代码发出请求时,它会给我“最后的垃圾”。 However, when I checked the response with JSON parser online. 但是,当我在线使用JSON解析器检查响应时。 It's a valid JSON. 这是有效的JSON。

Alamofire.request("http://myserver/list.svc/random", headers: headers).responseJSON { response in
    print(response)
}

I also tried making a request like this : 我也尝试过这样的请求

Alamofire.request("http://myserver/list.svc/random", headers: headers).responseString { response in
    print(response)
}

I am getting this message in console: "401 UNAUTHORIZED" . 我在控制台中收到此消息:“ 401 UNAUTHORIZED”

What am I doing wrong? 我究竟做错了什么? I believe, when using responseJSON completion block it's not complaining about Unauthorization , but it's complaining about bad JSON (or some garbage). 我相信,当使用responseJSON完成块时,它不是在抱怨Unauthorization ,而是在抱怨不良的JSON(或一些垃圾)。

PS The same request works fine with Advance Rest Client (a chrome extension) and also in chrome browser. PS相同的请求在Advance Rest Client(chrome扩展程序)和chrome浏览器中也能正常工作。

I don't know how relevant this is to you anymore but I've got a working solution I'll post for any future reference. 我不知道这对您有多重要,但是我有一个可行的解决方案,将在以后发布以供将来参考。

So, I had two issues. 所以,我有两个问题。 The first one being that the Authorization header fell of the request when it was redirected. 第一个是重定向请求时,Authorization标头属于请求。 The second one being the NTLM-challenge from the server not being handled. 第二个是未处理来自服务器的NTLM挑战。 The following code should be quite self explanatory I hope :) It asumes you store the username and password in variables name just that. 我希望下面的代码可以很容易地说明问题:)假设您将用户名和密码存储在变量名中。

    let credentialData = "\(username):\(password)".data(using: String.Encoding.utf8)!
    let base64Credentials = credentialData.base64EncodedString(options: [])
    request.addValue("Basic \(base64Credentials)", forHTTPHeaderField: "Authorization")

    let manager = Alamofire.SessionManager.default
    let delegate: Alamofire.SessionDelegate = manager.delegate

    // This bit will re-add the auth headers for the redirected request
    delegate.taskWillPerformHTTPRedirection = { session, task, response, request in
        var redirectedRequest = request

        if let originalRequest = task.originalRequest, let redirectheaders = originalRequest.allHTTPHeaderFields {
            if let authorizationHeaderValue = redirectheaders["Authorization"] {
                redirectedRequest.setValue(authorizationHeaderValue, forHTTPHeaderField: "Authorization")
            }
            if let contentTypeHeaderValue = redirectheaders["Content-Type"] {
                redirectedRequest.setValue(contentTypeHeaderValue, forHTTPHeaderField: "Content-Type")
            }
        }

        return redirectedRequest
    }

    // This bit looks at challenges received and applies the correct credentials
    delegate.taskDidReceiveChallenge = { session, task, challenge in
        var disposition: URLSession.AuthChallengeDisposition = .useCredential
        var credential: URLCredential = URLCredential()

        if (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodNTLM) {
            disposition = URLSession.AuthChallengeDisposition.useCredential
            credential = URLCredential(user: username, password: password, persistence: URLCredential.Persistence.forSession)
        }

        if (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust) {
            disposition = URLSession.AuthChallengeDisposition.useCredential
            credential = URLCredential(trust: challenge.protectionSpace.serverTrust!)
        }

        return(disposition, credential)
    }

    manager.request(request).responseData { (response) in
        // Handle response accordingly
    }

Hope this helps someone. 希望这对某人有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM