我搜索了很多,并且没有明确指示用" x-www-form-urlencoded"发送POST请求。内容类型。 我想知道如何做到这一点,如果你知道如何用Alamofire这样做,那将是一个更好的方法。 任何帮助将不胜感激。
答案 0 :(得分:18)
希望您正在搜索这个或在代码中给我们更多解释,以便我们轻松搞定:
let headers = [
"Content-Type": "application/x-www-form-urlencoded"
]
let parameters = [
]
Alamofire.request("urlString", method: .post, parameters: parameters, encoding: URLEncoding.httpBody, headers: headers).responseJSON { (response:DataResponse<Any>) in
switch(response.result) {
case.success(let data):
print("success",data)
case.failure(let error):
print("Not Success",error)
self.view.makeToast(message: "Server Error!!")
}
}
答案 1 :(得分:2)
我在Swift 4.2中使用了以下代码
guard let url = URL(string: "http://192.168.88.129:81/authenticate") else {
return
}
let user1 = username.text!
let pass = passwordfield.text!
print(user1)
print(pass)
let data : Data = "username=\(user1)&password=\(pass)&grant_type=password".data(using: .utf8)!
var request : URLRequest = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField:"Content-Type");
request.setValue(NSLocalizedString("lang", comment: ""), forHTTPHeaderField:"Accept-Language");
request.httpBody = data
print("one called")
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
// vs let session = URLSession.shared
// make the request
let task = session.dataTask(with: request, completionHandler: {
(data, response, error) in
if let error = error
{
print(error)
}
else if let response = response {
print("her in resposne")
}else if let data = data
{
print("here in data")
print(data)
}
DispatchQueue.main.async { // Correct
guard let responseData = data else {
print("Error: did not receive data")
return
}
let decoder = JSONDecoder()
print(String(data: responseData, encoding: .utf8))
do {
// let todo = try decoder.decode(T.self, from: responseData)
// NSAssertionHandler(.success(todo))
} catch {
print("error trying to convert data to JSON")
//print(error)
// NSAssertionHandler(.failure(error))
}
}
})
task.resume()
}
答案 2 :(得分:0)
使用Alamofire
Alamofire.request("yourSide", method: .post, parameters: parameters, encoding: URLEncoding.default)
如果它不起作用,这是不可能的,请使用以下代码
Alamofire.request("yourSide", method: .post, parameters: parameters, encoding: URLEncoding.httpBody)