【发布时间】:2017-09-15 11:14:22
【问题描述】:
我正在尝试使用 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)
}
我尝试在请求中添加值,可能是形成的请求中缺少某些值。请帮忙!
【问题讨论】:
-
还可以查看 AlamoFire pod,以更轻松地完成此操作。
-
@TheValyreanGroup 使用过 Alamofire,同样的问题也发生在那里。 API 在 POSTMAN 中运行良好
-
@TheValyreanGroup: 我的代码: let urlString = "xxx.xxxx.xxxx.xxx/login" let headers = [ "Content-Type": "application/form-data" ] Alamofire.request(urlString, method: .post , 参数: ["userName": userName,"password": password], 编码: JSONEncoding.default, headers: headers).responseJSON { response in switch response.result { case .success: print(response) break case .failure(让错误):打印(错误)}}
-
@TheValyreanGroup 工作。我的请求如下: Alamofire.request(urlString, method: .post, parameters: param).responseJSON { response in ,其中 param 是字典 & urlString 是 url。让参数:[字符串:字符串] = [“用户名”:“xxxx”,“密码”:“xxxx”]
-
@TheValyreanGroup 你得到这个答案了吗?
标签: post swift3 ios10 content-type form-data