问题
I am using two models GET and POST which are encodable and decodable
using the below code i am able to get the data in GET model, but i am not able to post the data with POST model.
please guide me how to post the data using POST model
let url = URL(string: "<YOUR URL HERE>")
let config = URLSessionConfiguration.default
config.httpAdditionalHeaders = [
"Accept" : "application/json",
"Content-Type" : "application/x-www-form-urlencoded"
]
let session = URLSession(configuration: config)
var request = URLRequest(url: url!)
request.encodeParameters(parameters: ["username": username, "password":
password])
let task = session.dataTask(with: request) { data, response, error in
guard let data = data else { return }
do {
let sentPost = try JSONDecoder().decode(Get.self, from: data)
print(sentPost)
} catch {}
}
task.resume()
model
struct Post: Encodable, Decodable {
let username: String
let password: String
}
extension for URLRequest
extension URLRequest {
private func percentEscapeString(_ string: String) -> String {
var characterSet = CharacterSet.alphanumerics
characterSet.insert(charactersIn: "-._* ")
return string
.addingPercentEncoding(withAllowedCharacters: characterSet)!
.replacingOccurrences(of: " ", with: "+")
.replacingOccurrences(of: " ", with: "+", options: [], range: nil)
}
mutating func encodeParameters(parameters: [String : String]) {
httpMethod = "POST"
let parameterArray = parameters.map { (arg) -> String in
let (key, value) = arg
return "\(key)=\(self.percentEscapeString(value))"
}
httpBody = parameterArray.joined(separator: "&").data(using: String.Encoding.utf8)
}
}
回答1:
You don't need to create another string and then to data. This will be handled by Codable protocol and your JSONEncoder. You need to encode your post type using JSONEncoder and provide the data to the request.httpBody
Try this:
let url = URL(string: "<YOUR URL HERE>")
let config = URLSessionConfiguration.default
config.httpAdditionalHeaders = [
"Accept" : "application/json",
"Content-Type" : "application/x-www-form-urlencoded"
]
do {
let aPost = Post(username: "username", password: "password")
let encoder = JSONEncoder()
let encodedPost = try encoder.encode(aPost)
let session = URLSession(configuration: config)
var request = URLRequest(url: url!)
request.httpMethod = "POST"
request.httpBody = encodedPost
let task = session.dataTask(with: request) { data, response, error in
do {
let sentPost = try JSONDecoder().decode(Get.self, from: data)
print(sentPost)
} catch {
print(error.localizedDescription)
}
}
task.resume()
} catch {
print(error.localizedDescription)
}
来源:https://stackoverflow.com/questions/50444422/how-to-post-the-data-in-encoding-structure