【问题标题】:Alamofire swift 3.1 post service call response as status code 400 the following is my codeAlamofire swift 3.1 post service call response as status code 400 以下是我的代码
【发布时间】:2018-03-03 15:11:52
【问题描述】:

var 参数 = 字符串:字符串

    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

让标头:HTTPHeaders = [ “内容类型”:“应用程序/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

        }

回复为:

{ 错误 = "invalid_request"; "error_description" = "缺少授权类型"; }

【问题讨论】:

  • 检查我的回答任何问题然后告诉我会帮助你

标签: ios swift3 alamofire


【解决方案1】:
 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
            }
    }

将参数转换为 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 ""
        }
    }

【讨论】:

  • 感谢@Himanshu Moradiya 的回答:)。我试过你的代码行得到的结果仍然是同样的错误:{ error = "invalid_request"; "error_description" = "缺少授权类型"; }
  • 我在 Postman 和 Restclient 中进行了检查,其 url 和参数作为 Bearer 令牌得到了积极响应
  • @Narasimha 我认为你必须将 grand_type 参数作为标题字段传递
  • 很奇怪,它在 Rest 客户端、Postman 和 android 中运行良好
  • 谢谢@Himanshu Moradiya 问题已通过转换为您的代码的 jsonstring 来解决。 :)
猜你喜欢
  • 1970-01-01
  • 2022-11-20
  • 2018-11-17
  • 2016-01-19
  • 2022-12-01
  • 2021-02-05
  • 1970-01-01
  • 2018-03-03
  • 2013-06-05
相关资源
最近更新 更多