Alamofire swift 3.1发布服务呼叫响应作为状态码400以下是我的代码

时间:2017-09-22 06:10:15

标签: ios swift3 alamofire

var parameters = String:String

    parameters["client_id"] = "trackmykid"
    parameters["client_secret"] = "trackmykid"
    parameters["grant_type"] = "password"
    parameters["roleId"] = "2"
    parameters["device_token"] = "12324567"
    parameters["os_type"] = "ios"
    parameters["username"] = username
    parameters["password"] = password

let headers:HTTPHeaders = [             “Content-Type”:“application / x-www-form-urlencoded”,             “授权”:“基本dHJhY2tteWtpZDp0cmFja215a2lk”             ]

    var Paramdict = [String: String]()

    Paramdict = ["client_id":"trackmykid","client_secret":"trackmykid","grant_type":"password","roleId":"2","device_token":"123456","os_type":"ios", "username":username,"password":password]


        Alamofire.request(Baseurl.appending("oauth/token"), method: .post, parameters: Paramdict as? Parameters, encoding: JSONEncoding.default, headers: headers).responseJSON { (response:DataResponse<Any>) in

        switch(response.result) {
        case .success(_):
            if response.result.value != nil{
                print(response.result.value ?? NSDictionary())

                onSuccess(response.result.value as! [AnyHashable : Any])

            }
            break

        case .failure(_):

            print(response.result.error  ?? NSString())

            onFailure(response.result.error!)

            break

        }

回复:

{error =“invalid_request”; “error_description”=“缺少授权类型”; }

1 个答案:

答案 0 :(得分:0)

 let myParams = "UserName=\(txtemailaddress.text!)&Password=\(txtpassword.text!)&Grant_type=password&DeviceID=\(DEVICE_TOKEN as! String)&DeviceType=IOS"
    let postData = myParams.data(using: String.Encoding.ascii, allowLossyConversion: true)
    let postLength = String(format: "%d", postData!.count)
    print(myParams)
    let myRequest = NSMutableURLRequest(url: url)
    myRequest.httpMethod = "POST"
    myRequest.setValue(postLength, forHTTPHeaderField: "Content-Length")
    myRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    myRequest.httpBody = postData

  let str = AppUtilities.sharedInstance.jsonToString(json: mainParam)

 Alamofire.request(myRequest as URLRequestConvertible)
        .responseJSON { response in
            // do whatever you want here

            switch response.result {
            case .success(let value):
                let result = Result.success(value)
                print(result)
                let json = try? JSONSerialization.jsonObject(with: response.data!, options: [])
                let Response : NSDictionary = json as! NSDictionary
                print(Response)

                if Response.value(forKey: "success") as! String == "1"{
                   // GOT RESPONSE SUCCESS 
                }
                else{
                    KRProgressHUD.dismiss()
                    AppUtilities.sharedInstance.showAlert(title: "Error", msg: Response.value(forKey: "message") as! NSString)
                }

                break
            case .failure:
                let result = Result<Data>.failure

                KRProgressHUD.dismiss()
                print("exception: \(response.result.error)")

                break
            }
    }

将Param转换为JSON字符串的代码

  func jsonToString(json: AnyObject) -> String{
        do {
            let data1 =  try JSONSerialization.data(withJSONObject: json, options: JSONSerialization.WritingOptions.prettyPrinted) // first of all convert json to the data
            let convertedString = String(data: data1, encoding: String.Encoding.utf8) // the data will be converted to the string
            print(convertedString!) // <-- here is ur string
            return convertedString!
        } catch let myJSONError {
            print(myJSONError)
            return ""
        }
    }