我就是这么做的
var request = URLRequest(url: url)
let methodString = mehtod.rawValue
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.cachePolicy = .reloadIgnoringLocalAndRemoteCacheData
if let headers = headers {
request.set(headers: headers)
}
if let parameters = parameters {
do {
let postParams = try JSONEncoder().encode(parameters)
let postData = postParams
request.httpBody = postData
}
catch {
print("error")
}
}
let session = URLSession.shared
print(request)
print(request.allHTTPHeaderFields)
print(String(data: request.httpBody!, encoding: .utf8)!)
print(request.httpMethod)
session.dataTask(with: request) { (data, response, error) in
let result: Result<Data>
if let data = data {
result = .success(data)
}
else if let error = error {
result = .failure(error)
}
else {
result = .failure(RESTError.unknownError)
}
completion(result)
}.resume()
这就是我在查尔斯身上看到的
我试着发邮件,但不知怎的我发了GET请求。
另外,我从服务器得到错误:
{"message":"Method \"GET\" not allowed.","code":"method_not_allowed"}
原因可能是什么?
最佳答案
我想你可以使用session.uploadTask(with: request, from: uploadData)
。