使用 Content-Type 发出 Alamofire 请求:multipart/form-data
Posted
技术标签:
【中文标题】使用 Content-Type 发出 Alamofire 请求:multipart/form-data【英文标题】:making Alamofire Request with Content-Type: multipart/form-data 【发布时间】:2019-04-23 11:13:58 【问题描述】:我想用 Alamofire 发出 post 请求,接收带有 Content-Type: multipart/form-data
的请求并接受有效负载文件在邮递员中并且它可以工作,注意在发出请求后我不希望回复它会是空的
let body: [String:String] = [
"id":"101",
"message":test,
"type":"test"
]
let payload = [
"payload":body
]
let headers = [ "Content-Type" : "multipart/form-data"]
Alamofire.request("URL", method: .post, parameters:payload, encoding: JSONEncoding.default, headers: headers).responseObject (response: DataResponse<ObjectEntity>) in
guard (response.response?.statusCode == 200 || response.response?.statusCode == 204) else
if response.response != nil
self.showAPILogs(fullURL: self.getFullURL(methodName: methodName), response: response.response, statusCode: response.response!.statusCode)
return
self.showAPILogs(fullURL: self.getFullURL(methodName: methodName), response: response.response, statusCode: response.response!.statusCode)
【问题讨论】:
Send POST parameters with MultipartFormData using Alamofire, in ios Swift的可能重复 您在“multipartb/form-data”中有错字 但是如何发送带有访问令牌的标头? 使用alamofire的这个功能upload( multipartFormData: @escaping (MultipartFormData) -> Void, usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold, with urlRequest: URLRequestConvertible, encodingCompletion: ((SessionManager.MultipartFormDataEncodingResult) -> Void)?)
我收到“所需的请求部分'有效负载'不存在”
【参考方案1】:
试试
let body: [String: String] = [
"id": "101",
"message": test,
"type": "test"
]
Alamofire.upload(multipartFormData: MultipartFormData in
for (key, value) in body
MultipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
, usingThreshold: UInt64.init(),
to: "URL",
method: .post,
headers: ["Authorization": "Your access token"], // As per the web service requirement
encodingCompletion: encodingResult in
switch encodingResult
case .success(let upload, _, _):
upload.responseJSON response in
case .failure(let error):
print(error)
)
看看它是否有效。
【讨论】:
这样的工作我收到消息 = "所需的请求部分'有效负载'不存在"; 在这种情况下,尝试将正文字典转换为 JSON 字符串并将其传递给有效负载,例如 let payload = [ "payload": "id": "101","message": test,"type ": "test" ] 并将 for-in 循环更改为 for (key, value) in payload MultipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key) 我正在努力将字典转换为 JSON 的部分,我不知道如何完成 如果让 jsonData = 试试? JSONSerialization.data ( withJSONObject: bodyDictionary, options: [] ), let jsonString = String(data: jsonData, encoding: String.Encoding.utf8) print(“JSON String is: (jsonString)”)以上是关于使用 Content-Type 发出 Alamofire 请求:multipart/form-data的主要内容,如果未能解决你的问题,请参考以下文章
如何使用“Content-type:application/x-www-form-urlencoded”发出 Okhttp 请求?
如何在使用 Cloud Scheduler 发出的 HTTP POST 请求上添加 JSON 正文?它会添加“Content-Type”:“application/json”标头吗?