gpt4 book ai didi

post - 如何在Swift 3中的POST请求中发送表单数据

转载 作者:行者123 更新时间:2023-12-04 16:25:35 26 4
gpt4 key购买 nike

我正在尝试使用Web服务,用户名和密码发布表单数据,但作为响应,它显示了一条错误消息,指出“无法连接到服务器”。

请帮助我在POST请求中发送表单数据。

        let dict:[String:String] = ["userName": userName as! String, "password": password as! String]

do {

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

let url = URL(string: "(some url)")!

var request = URLRequest(url: url)

request.httpMethod = "POST"

request.setValue("application/x-www-form-urlencoded charset=utf-8", forHTTPHeaderField: "Content-Type")

request.httpBody = jsonData

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

if error != nil {

print(error!.localizedDescription)

return

}

do {

let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary

if let parseJSON = json {

let resultValue:String = parseJSON["success"] as! String;

print("result: \(resultValue)")

print(parseJSON)

}

} catch let error as NSError {

print(error)

}
}

task.resume()

} catch {

print(error.localizedDescription)

}

我尝试在请求中添加值,可能是所形成的请求中缺少某些值。请帮忙!

Thats the POSTMAN response

最佳答案

我的调用API类别

class ApiService
{
static func getPostString(params:[String:Any]) -> String
{
var data = [String]()
for(key, value) in params
{
data.append(key + "=\(value)")
}
return data.map { String($0) }.joined(separator: "&")
}

static func callPost(url:URL, params:[String:Any], finish: @escaping ((message:String, data:Data?)) -> Void)
{
var request = URLRequest(url: url)
request.httpMethod = "POST"

let postString = self.getPostString(params: params)
request.httpBody = postString.data(using: .utf8)

var result:(message:String, data:Data?) = (message: "Fail", data: nil)
let task = URLSession.shared.dataTask(with: request) { data, response, error in

if(error != nil)
{
result.message = "Fail Error not null : \(error.debugDescription)"
}
else
{
result.message = "Success"
result.data = data
}

finish(result)
}
task.resume()
}
}

以及何时使用
ApiService.callPost(url: url, params: params, finish: finishPost)

和完成功能
func finishPost (message:String, data:Data?) -> Void
{
do
{
if let jsonData = data
{
let parsedData = try JSONDecoder().decode(Response.self, from: jsonData)
print(parsedData)
}
}
catch
{
print("Parse Error: \(error)")
}
}

关于post - 如何在Swift 3中的POST请求中发送表单数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43492089/

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