Swift 5 & Alamofire 5 : GET method ERROR: Alamofire.AFError.URLRequestValidationFailureReason.bodyDataInGETRequest(22 bytes)

两盒软妹~` 提交于 2020-05-17 06:32:25

问题


I am trying to get records from Database using Alamofire. I am sending parameters in GET request as below.

let headers : HTTPHeaders = ["x-access-token": "\(t)","username":"\(Base.sharedManager.user)","password":"\(Base.sharedManager.pass)"]
let parm : [String: Any] = ["search_str" : self!.searchStr]
// let searchUrl = Base.sharedManager.URL+"questions/get/"+self!.searchStr
let searchUrl = Base.sharedManager.URL+"questions/get/"

AF.request(searchUrl, method: .get, parameters: parm, encoding:JSONEncoding.default , headers: headers, interceptor: nil).response { (responseData) in
    guard let data = responseData.data else {
        debugPrint("Error getting question data", responseData.error as Any)
        self?.showNoResults()
        return
    }

    do {
        let sResults = try JSONDecoder().decode(SearchResults.self, from: data)
        self!.searchReturn = [sResults]
        self!.qSearchTV.reloadData()
    } catch {
        self?.showNoResults()
        print("Error retriving questions \(error)")
    }                        
}

Got the error below when above code executed: "Error getting question data" Optional(Alamofire.AFError.urlRequestValidationFailed(reason: Alamofire.AFError.URLRequestValidationFailureReason.bodyDataInGETRequest(23 bytes)))


回答1:


Alamofire 5 and Apple's 2019 frameworks now produce an error when you try to make a GET request with body data, as such a request is invalid. I would suggest checking to make sure that's what your server is expected, and if it does really require body data for GET requests, reach out to the API provider and request a change, as no device running Apple's 2019 OSes will be able to make such a request.




回答2:


You have to remove the "parameters" parameter.

Instead of doing this:

AF.request("https://httpbin.org/get",
              method: .get,
              parameters: [:],
              encoding: URLEncoding.httpBody,
              headers: [:])

Do this:

AF.request("https://httpbin.org/get",
              method: .get,
              encoding: URLEncoding.httpBody,
              headers: [:])


来源:https://stackoverflow.com/questions/60960976/swift-5-alamofire-5-get-method-error-alamofire-aferror-urlrequestvalidation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!