gpt4 book ai didi

json - 如何通过 Swift 发送 POST 请求?

转载 作者:IT王子 更新时间:2023-10-29 05:33:14 24 4
gpt4 key购买 nike

我有这样的 Controller -

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 发出此请求时,我选择正文,然后形成数据并添加电子邮件和密码。这行得通

enter image description here

如何使用 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()

最佳答案

我创建了一个自定义 HTTP 类,我们可以在其中发送 url、参数,我们将从 API 获取数据。下面是类(class)。

import Foundation

//HTTP Methods
enum HttpMethod : String {
case GET
case POST
case DELETE
case PUT
}


class HttpClientApi: NSObject{

//TODO: remove app transport security arbitary constant from info.plist file once we get API's
var request : URLRequest?
var session : URLSession?

static func instance() -> HttpClientApi{

return HttpClientApi()
}



func makeAPICall(url: String,params: Dictionary<String, Any>?, method: HttpMethod, success:@escaping ( Data? ,HTTPURLResponse? , NSError? ) -> Void, failure: @escaping ( Data? ,HTTPURLResponse? , NSError? )-> Void) {

request = URLRequest(url: URL(string: url)!)

logging.print("URL = \(url)")

if let params = params {


let jsonData = try? JSONSerialization.data(withJSONObject: params, options: .prettyPrinted)

request?.setValue("application/json", forHTTPHeaderField: "Content-Type")
request?.httpBody = jsonData//?.base64EncodedData()


//paramString.data(using: String.Encoding.utf8)
}
request?.httpMethod = method.rawValue


let configuration = URLSessionConfiguration.default

configuration.timeoutIntervalForRequest = 30
configuration.timeoutIntervalForResource = 30

session = URLSession(configuration: configuration)
//session?.configuration.timeoutIntervalForResource = 5
//session?.configuration.timeoutIntervalForRequest = 5

session?.dataTask(with: request! as URLRequest) { (data, response, error) -> Void in

if let data = data {

if let response = response as? HTTPURLResponse, 200...299 ~= response.statusCode {
success(data , response , error as? NSError)
} else {
failure(data , response as? HTTPURLResponse, error as? NSError)
}
}else {

failure(data , response as? HTTPURLResponse, error as? NSError)

}
}.resume()

}

}

现在您可以引用下面的代码来了解如何进行 API 调用。

  var paramsDictionary = [String:Any]()

paramsDictionary["username"] = "BBB"
paramsDictionary["password"] = "refef"

HttpClientApi.instance().makeAPICall(url: "Your URL", params:paramsDictionary, method: .POST, success: { (data, response, error) in

// API call is Successfull

}, failure: { (data, response, error) in

// API call Failure

})

关于json - 如何通过 Swift 发送 POST 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43907542/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com