I am trying to make an api request which type is "multipartFormData", is working completely fine with Alamofire but getting failed when uisng URLSession
Alamofire
func alamoFire(){
let operatorID = "24601"
let custName = "PEp"
let dcName = "Richasox"
let bucketName = "s3BucketXXX"
let headers: HTTPHeaders = [
"Content-type": "multipart/form-data",
"x-api-key" : "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
]
AF.upload(
multipartFormData: { multipartFormData in
multipartFormData.append(operatorID.data(using: .utf8)!, withName: "pickerId")
multipartFormData.append(dcName.data(using: .utf8)!, withName: "dcName")
multipartFormData.append(custName.data(using: .utf8)!, withName: "custName")
multipartFormData.append(bucketName.data(using: .utf8)!, withName: "bucketName")
},
to: "https://xxx.us-east-2.amazonaws.com/endpoint", method: .post , headers: headers)
.validate(statusCode: 200..<300)
.response { resp in
switch resp.result{
case .failure(let error):
print(error)
case.success( _):
print("Response after upload Img: \(resp.result)")
}
}
}
URLSession
func urlSession() {
let operatorID = "24601"
let custName = "PEPSI%20CORPORATE"
let dcName = "Richardson%20DC"
let bucketName = "picker-images-upload-rehrig"
let url = URL(string: "https://xxx.us-east-2.amazonaws.com/endpoint")
let boundary = UUID().uuidString
let session = URLSession.shared
var urlRequest = URLRequest(url: url!)
urlRequest.httpMethod = "POST"
urlRequest.setValue("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", forHTTPHeaderField: "x-api-key")
urlRequest.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
var data = Data()
data.append("\r\n--\(boundary)\r\n".data(using: .utf8)!)
data.append("Content-Disposition: form-data;pickerId=\"\(operatorID)\"; dcName=\"\(dcName)\"; bucketName=\"\(bucketName)\"; custName=\"\(custName)\"\r\n".data(using: .utf8)!)
data.append("\r\n".data(using:.utf8)!)
session.uploadTask(with: urlRequest, from: data, completionHandler: { responseData, response, error in
if error == nil {
let jsonData = try? JSONSerialization.jsonObject(with: responseData!, options: .allowFragments)
if let json = jsonData as? [String: Any] {
print("picker resp",json)
}
}
}).resume()
}
Error when using URLSession
Optional<NSURLResponse>
- some : <NSHTTPURLResponse: 0x283f8f4a0> { URL: https://xxx.us-east-2.amazonaws.com/endpoint } { Status Code: 502, Headers {
"Content-Length" = (
36
);
"Content-Type" = (
"application/json"
);
Date = (
"Sat, 15 Jan 2022 16:57:05 GMT"
);
Via = (
"1.1 62f7aa308c367fb8f14fc57f199056cc.cloudfront.net (CloudFront)"
);
"x-amz-apigw-id" = (
"L_xzJGBIiYcFfAA="
);
"x-amz-cf-id" = (
"2M2PlnPLZ8k_91htcX4OM4UL2a5ldOfntUbVO3xxMp702m9MMr0Elw=="
);
"x-amz-cf-pop" = (
"BLR50-C3"
);
"x-amzn-errortype" = (
InternalServerErrorException
);
"x-amzn-requestid" = (
"b7de8e82-06fe-41e0-9deb-0f2783aeea89"
);
"x-cache" = (
"Error from cloudfront"
);
} }