Post 方法没有在 api 调用中发送我的数据

Posted

技术标签:

【中文标题】Post 方法没有在 api 调用中发送我的数据【英文标题】:Post method is not sending my data in api call 【发布时间】:2018-04-24 06:33:10 【问题描述】:

您好,我是 swift 新手,我做了以下 api 调用来发送数据,但它没有发送,我得到了以下响应。

发送数据

firstName=gggg&lastName=ggg&username=fgg&password=ghh&email=ggg@gg.com&latitude=25.0710693470323&longitude=55.143004052641

回复

responseString  "status":"error","message":"Oops!!!Something went wrong..."

但我可以获得所有其他验证消息,例如“用户名不能为空”。

但我尝试使用 Postman 它在标题方法上也给出了与上面相同的错误消息,但后来我发现并发送了 Body Method 和 application/x-www-form-urlencoded 的形式,然后我得到了如下的成功响应。

以下是我的 API 调用...请有人找出我做错了什么或建议我更好的发布 api 调用。

还有一件事,这是我为“/homefeed”创建的相同 API 调用方法并获得了响应,但我们不需要为此发送任何特定参数。请帮帮我。

 func addNewUser()
    
        let url = URL(string: "https://xxxxxxxxxx.azurewebsites.net/api/addUser")!

        let firstName:String = firstnameTextFeild.text!
        let lastName:String = lastNameTxtField.text!
        let username:String = usernameTextField.text!
        let password:String = passwordTextField.text!
        let email:String = emailTextField.text!
        var request = URLRequest(url: url)
        request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
        request.httpMethod = "POST"
        let postString = "firstName=\(firstName)&lastName=\(lastName)&username=\(username)&password=\(password)&email=\(email)&latitude=\(lat)&longitude=\(long)"
        print("Sent Data -",postString)
        request.httpBody = postString.data(using: .utf8)
        /*
        do 
            request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) // pass dictionary to nsdata object and set it as request body

         catch let error 
            print(error.localizedDescription)
        
       */
        let task = URLSession.shared.dataTask(with: request)  data, response, error in
            guard let data = data, error == nil else                                                  // check for fundamental networking error
                print("error=\(String(describing: error))")
                return
            

            if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200            // check for http errors
                print("statusCode should be 200, but is \(httpStatus.statusCode)")
                print("response = \(String(describing: response))")
            

            let responseString = String(data: data, encoding: .utf8)

            // print("responseString = \(String(describing: responseString))")
            print("responseString ", responseString ?? "resSt")


        
        task.resume()

    

【问题讨论】:

这会帮助你:***.com/questions/26364914/… @Rocky 我正在使用该帖子中的相同 api 调用。我可以获得那些没有参数要发送的 api 的成功响应。但是当我发送参数时,我收到“出现错误消息” 取消注释JSONSerialization 语句,将application/x-www-form-urlencoded; charset=utf-8 添加到Content-Type,并将parameters 变量添加到您的问题中。 【参考方案1】:

使用此代码。它为您工作。

安装 podfile

pod 'Alamofire'

在你的 ViewController 中导入 Alamofire

func addNewUser()
let url = "your URL"
var param : [String : AnyObject] = [:]

param = ["firstName": firstnameTextFeild.text! as AnyObject,
         "lastName": lastNameTxtField.text! as AnyObject,
         "username": usernameTextField.text! as AnyObject,
         "password": passwordTextField.text! as AnyObject,
         "email": emailTextField.text! as AnyObject,
         "latitude": "your latitude" as AnyObject,
         "longitude": "your longitude" as AnyObject]
print(param)
Alamofire.request(url, method: .post, parameters: param, encoding: URLEncoding()).responseJSON  (response:DataResponse<Any>) in
    print(response)

    if (response.result.value != nil) 
        //your code
    
    else
        //your code
    
  

【讨论】:

不,我还是一样 我尝试了许多不同的发布方法,但我得到了相同的信息 是的,我仔细检查了参数是否正确,您可以查看问题中的邮递员截图 当参数不正确的时候才会出现这种问题。 我有一些用于此 api 的可选参数,我将尝试使用所有参数并让您知道.. 感谢您的大力帮助【参考方案2】:

你应该像这样传递你的参数:

  let passingDict : [String:Any] = [
                                     "fname" : YourValue,
                                      "lname":YourValue,
                                      "email" : YourValue,
                                      "password" : YourValue,
                                      "countryCode": YourValue,
                                      "mobileNumber": YourValue,
                                      "verificationType":YourValue,

                                     ]

  let signup_url = ApiList.base_url + ApiList.signup_url

  singletonclass.instance.Post_API_Call(passingDict, Url: signup_url, HittingApi: "SIGN_UP_URL")



func Post_API_Call(_ Parame: NSDictionary, Url: String, HittingApi: String)
    
        var Api_Resp_Err = String()
        var Api_Resp_Dict = NSDictionary()

        do

        
            let jsonData = try JSONSerialization.data(withJSONObject: Parame, options: [])
            let fullListURL = Url
            let url = URL(string: Url)!

            var request = URLRequest(url: url)

            request.httpMethod = "POST"

            request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")

            request.httpBody = jsonData

            let task = URLSession.shared.dataTask(with: request)  data,response,error in

                if error != nil 

                    DispatchQueue.main.async(execute: 

                        Api_Resp_Err = (error?.localizedDescription)!

                    )

                    return
                
                do
                
                    if let responseJSON = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary
                    
                        if  responseJSON.count > 0
                        
                            DispatchQueue.main.async(execute: 

                                let statusCode = responseJSON.object(forKey: "code") as? String ?? ""
                                let message = responseDict.object(forKey: "Message") as? String ?? ""


                            )
                        
                        else
                        


                        
                    
                    else
                    
                        DispatchQueue.main.async(execute: 

                            Api_Resp_Err = "Data Issue"

                        )
                    
                
                catch
                
                    DispatchQueue.main.async(execute: 

                        Api_Resp_Err = "Catch Issue"


                    )

                
            
            task.resume()
        
        catch
        
            DispatchQueue.main.async(execute: 
                //print("Server Issue catch II")
            )
        

    

【讨论】:

以上是关于Post 方法没有在 api 调用中发送我的数据的主要内容,如果未能解决你的问题,请参考以下文章

将雪花数据发送到 REST API (POST) 的方法

在 Django 视图中调用“request.POST”时,Ajax POST 不发送数据

使用 MVC 从数据主体调用 post API

如何在 jQuery AJAX 调用中发送所有当前的帖子数据

当我们在ColdFusion中使用API 调用(POST请求)将参数数量传递给服务器时,如何修复“POST请求超出”错误?

Python Post 请求 - 通过 Outlook API 发送文件时出现 415 错误