在Swift中使用基本身份验证的POST请求+获取params + post params(使用Alamofire或RxSwift或其他任何东西)

时间:2016-06-26 06:42:45

标签: swift

我尝试发送POST请求 在服务器http://test.alex009.ru/上设置HTTP身份验证(alice / Qwerty1234)

执行查询:

使用参数传输POST http://test.alex009.ru/alice.php

获取参数是“秘密”= alex009 post参数“input”=(从文本字段输入的文本)

标头中的

必须指定接收内容的类型 - application / json

我的代码是:

我有这个用于HTTP基本身份验证

let username = "alice"
let password = "Qwerty1234"
let loginString = NSString(format: "%@:%@", username, password)
let loginData: NSData = loginString.dataUsingEncoding(NSUTF8StringEncoding)!
let base64LoginString = loginData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions())
let authenticationToken = base64LoginString

我需要发布thith get参数:

let parameters : [String: AnyObject] = ["secret" : "alex009"]

然后我创建了NSMutableURLRequest:

let url = NSURL(string: "http://test.alex009.ru/alice.php")
        var request = NSMutableURLRequest(URL: url!)
        request.HTTPMethod = "POST"
        let encoding = Alamofire.ParameterEncoding.JSON
        (request, _) = encoding.encode(request, parameters: parameters)
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")
        let values = ["input" : "textFromTextFild"]
        request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(values, options: [])
        print(request)

并将其发送给Alamofire:

Alamofire.request(request)
            .validate()
            .responseJSON { response in
                // do whatever you want here
                switch response.result {
                case .Failure(let error):
                    print(error)
                case .Success(let responseObject):
                    print(responseObject)
                }
        }

并从服务器获取响应:

{URL:my url} Error Domain = com.alamofire.error Code = -6003“响应状态代码不可接受:406”UserInfo = {NSLocalizedFailureReason =响应状态代码不可接受:406}

我的错误在哪里?

1 个答案:

答案 0 :(得分:0)

let headers = ["Content-Type": "application/json"]

let params: Parameters = [ "paramsString": param]


Alamofire.request( baseUrlDev, method: .post, parameters:params, encoding: JSONEncoding.default, headers: headers).responseJSON {(response: DataResponse<Any>) in
            
            switch(response.result) {
            case .success(_):
                if let data = response.result.value{
                    HyberLogger.debug(response.result.value)
                    
                }
                break
                
            case .failure(_):HyberLogger.debug("Unknown Error")
                    }
                }
                
                break
            }
        }