gpt4 book ai didi

ios - 如何使用 swift 发出 HTTP Post 请求

转载 作者:行者123 更新时间:2023-11-30 12:55:24 25 4
gpt4 key购买 nike

typealias ServiceResponse = (JSON, NSError?) -> Void
class RestApiManager: NSObject {
static let sharedInstance = RestApiManager()
let baseURL = "http://api.randomuser.me/"
func postUser(){}
func getRandomUser(onCompletion: (JSON) -> Void) {
let route = baseURL
makeHTTPGetRequest(route, onCompletion: { json, err in
onCompletion(json as JSON)
})
}
func makeHTTPGetRequest(path: String, onCompletion: ServiceResponse) {
let request = NSMutableURLRequest(URL: NSURL(string: path)!)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
let json:JSON = JSON(data: data)
onCompletion(json, error)
})
task.resume()
}
func makeHTTPPostRequest(path: String, body: [String: AnyObject], onCompletion: ServiceResponse) {
var err: NSError?
let request = NSMutableURLRequest(URL: NSURL(string: path)!)
// Set the method to POST
request.HTTPMethod = "POST"
// Set the POST body for the request
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(body, options: nil, error: &err)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
let json:JSON = JSON(data: data)
onCompletion(json, err)
})
task.resume()
}
}

如何在 ViewController 中调用 httppost 方法 postuser 并将 header + 编码参数传递给它?

喜欢 http://www.api.com/post/data?username=kr%209&password=12我还需要在 ehader 中发送 session /cookie/useragent。

最佳答案

request.setValue("Your Header value", forHTTPHeaderField: "Header-Key") //User-Agent for ex.

关于ios - 如何使用 swift 发出 HTTP Post 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40460470/

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