无法使用URLRequest发送帖子请求

问题描述

我正在尝试通过URLSession发送帖子请求

我正在以此构建我的有效载荷

let params: [String : Any] = [
                "name": username,"password": password,"email": email,"c_password": confirmPassword
            ]

与此同时

var urlParser = URLComponents()
            urlParser.queryItems = [
                URLQueryItem(name: "name",value: username),URLQueryItem(name: "password",value: password),URLQueryItem(name: "email",value: email),URLQueryItem(name: "c_password",value: confirmPassword)
            ]

并将其设置为httpBody这样

 request.httpBody = parameters.data(using: .utf8)

调用我的函数,但会引发错误

The request was well formed but was unable to be followed due to semantic errors

但是当我尝试以这种方式发送请求

let parameters = "name=test&password=Pass@123&c_password=Pass@123&email=test111@gmail.com"

有效

但是当我尝试使其动态化

let parameters = "name=\(username)&password=\(password)&c_password=\(confirmPassword)&email=\(email)"

它给了我错误。 我不确定自己在做什么错

完整代码

if let url = URL(string: Constants.REGISTRATION_URL){
            var request = URLRequest(url: url)
            request.httpMethod = "POST"
            let params: [String : Any] = [
                "name": username,"c_password": confirmPassword
            ]
            var urlParser = URLComponents()
            urlParser.queryItems = [
                URLQueryItem(name: "name",value: confirmPassword)
            ]
          //  let httpBodyString = urlParser.percentEncodedQuery
           // let parameters = "name=test&password=Pass@123&c_password=Pass@123&email=test111@gmail.com"
            let parameters  = "name=\(username)&password=\(password)&c_password=\(confirmPassword)&email=\(email)"
          
            request.addValue("Application/x-www-form-urlencoded",forHTTPHeaderField:"Content-Type")
             request.httpBody = parameters.data(using: .utf8)
            apimanager.sharedInstance.postCall(request: request,onSuccess: { json in
                dispatchQueue.main.async {
                    
                    
                }
            },onFailure: { error in
                do{
                    let errorModel = try JSONDecoder().decode(ErrorModel.self,from: Data(error.utf8))
                    dispatchQueue.main.async {
                        self.showAlertMessage(alertMessage: errorModel.errors[0].detail)
                    }
                }catch{
                    dispatchQueue.main.async {
                        self.showAlertMessage(alertMessage: error.localizedDescription)
                    }
                }
            })
        }

解决方法

问题是您正在尝试将GET查询字符串发送到POST请求。

GET请求要求使用字符转义的字符串(如您所拥有的字符串)。

POST请求期望(主要是)字典对象(例如您的param字典)

See this answer for how to set a POST request properly