json – 如何通过Swift发送POST请求?
发布时间:2020-12-14 19:59:07 所属栏目:百科 来源:网络整理
导读:我有这样的控制器 – def create if (@user = User.find_by_email(params[:email])) @user.valid_password?(params[:password]) render json: @user.as_json(only: [:email,:authentication_token]),status: :created else render json:('Unauthorized Acces
我有这样的控制器 –
def create if (@user = User.find_by_email(params[:email])) && @user.valid_password?(params[:password]) render json: @user.as_json(only: [:email,:authentication_token]),status: :created else render json:('Unauthorized Access') end end 当我使用Postman发出此请求时,我选择Body,并形成数据并添加电子邮件和密码.这个工作 如何使用swift做同样的事情?这就是我的尝试 let url = URL(string: "http://localhost:3000/api/v1/user_serialized/") let config = URLSessionConfiguration.default let request = NSMutableURLRequest(url: url!) request.httpMethod = "POST" let bodyData = "email=Test@test.com&password=Test1234" request.httpBody = bodyData.data(using: String.Encoding.utf8); let session = URLSession(configuration: config) let task = session.dataTask(with: url! as URL,completionHandler: {(data,response,error) in let json = JSON(data:data!) debugPrint(json) }) task.resume() 解决方法
我认为你应该将你的请求而不是url传递给session.dataTask
这是我的代码的样子: private let url = URL(string: "http://example.com/")! func httpPost(jsonData: Data) { if !jsonData.isEmpty { var request = URLRequest(url: url) request.httpMethod = "POST" request.httpBody = jsonData URLSession.shared.getAllTasks { (openTasks: [URLSessionTask]) in NSLog("open tasks: (openTasks)") } let task = URLSession.shared.dataTask(with: request,completionHandler: { (responseData: Data?,response: URLResponse?,error: Error?) in NSLog("(response)") }) task.resume() } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |