使用Content-Type制作Alamofire请求:multipart / form-data

问题描述 投票:0回答:1

我想向Alamofire提出请求,使用Content-Type: multipart/form-data接受请求并接受有效负载文件我尝试发出请求,因为您可以从代码中看到,但我收到500错误代码,我确实在Postman中提出相同的请求并且它工作,在提出请求后请注意我不希望回复它将是空的

  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)


            }
ios swift alamofire
1个回答
0
投票

尝试

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)
        }
    })

看看它是否有效

© www.soinside.com 2019 - 2024. All rights reserved.