在 Swift 中发出基本的 post 请求,并且值在 $_POST 数组的键中接收。
快速代码:
struct TestResponse: Codable{
let test: String
}
func postData<T:Codable>( parameters: T, completion: @escaping (Data?, URLResponse?, Error?) -> Void) {
let urlString = "http://example.com"
var request = URLRequest(url: URL(string: urlString)! )
request.addValue("XMLHttpRequest", forHTTPHeaderField: "X-Requested-With")
request.setValue("application/json, text/javascript, /; q=0.01", forHTTPHeaderField: "Accept")
request.httpMethod = "POST"
request.httpBody = try! JSONEncoder().encode(parameters)
URLSession.shared.dataTask(with: request) { data, response, error in
completion(data, response, error)
}.resume()
}
//sent variable as parameters
let test = TestResponse(test: "string with space")
我得到的是:
[{"test":"string_with_space"}] =>
看起来像 $_POST 数组的键中的整个序列化 JSON 字符串,以及它的空值。 我对此很陌生。我确信我缺少诸如标题之类的东西。
我试图将请求作为帖子键中的变量名称和 $_POST 值中的变量值分发到 PHP post 请求中。
因此,我找到的解决方案是将请求正文视为字符串,并为要在发布请求中发送的每个项目设置内容配置:
func createMultipartBody(boundary:String, parameters: [String: String], images: [UIImage]) -> Data {
let body = NSMutableData()
// Add parameters
for (key, value) in parameters {
body.appendString("--\(boundary)\r\n")
body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
body.appendString("\(value)\r\n")
}
body.appendString("--\(boundary)--\r\n")
return body as Data
}
这是一个为我创建发布请求的函数:
func postDataRequest( parameters: [String:String], action: String, completion: @escaping (Data?, URLResponse?, Error?) -> Void) {
let boundary = "Boundary-\(UUID().uuidString)"
let body = createMultipartBody(boundary:boundary, parameters: parameters)
guard let baseURL = UserDefaults.standard.string(forKey: "baseURL") else { return }
guard let url = URL(string: "\(baseURL)/\(action)") else { return }
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
request.setValue(String(body.count), forHTTPHeaderField: "Content-Length")
request.addValue("XMLHttpRequest", forHTTPHeaderField: "X-Requested-With")
request.httpBody = body
URLSession.shared.dataTask(with: request) { data, response, error in
completion(data, response, error)
}.resume()
}
要发送图像,您还必须根据图像 mimetype 设置内容类型,并附加图像数据。此示例适用于 jpeg,图像是 UIImage 对象:
if let imageData = image.jpegData(compressionQuality: 0.7) {
let filename = "\(UUID().uuidString).jpg"
let mimetype = "image/jpeg"
body.appendString("--\(boundary)\r\n")
body.appendString("Content-Disposition: form-data; name=\"images[]\"; filename=\"\(filename)\"\r\n")
body.appendString("Content-Type: \(mimetype)\r\n\r\n")
body.append(imageData)
body.appendString("\r\n")
}