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



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

让标头: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" ="缺少赠款类型";}

 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 String

  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 ""
        }
    }

最新更新