Image upload along with parameters not working with the below code i tried.
let testImage = UIImage(named: "sayHi")
let headers: HTTPHeaders = [
"Content-type": "multipart/form-data",
"Content-lenth" : "\(testImage?.pngData()?.count ?? 0)",
"Accept": "application/json",
]
AF.upload(
multipartFormData: { multipartFormData in
multipartFormData.append("10".data(using: .utf8)!, withName: "pickerId")
multipartFormData.append("100".data(using: .utf8)!, withName: "walkerRfid")
multipartFormData.append(testImage!.pngData()!, withName: "photo" , fileName: "file.png", mimeType: "image/png")
},
to: "https://zb9.amazonaws.com/data/savePickerData", 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)")
}
}
Response :
responseValidationFailed(reason: Alamofire.AFError.ResponseValidationFailureReason.unacceptableStatusCode(code: 502))
Related
I have a problem when I make a http request to the server
when I post on flutter it returns NO_RENEGOTIATION(ssl_lib.cc:1725) error 268435638 error, but when I try to use postman it works fine.
I've equated all the headers with postman, replaced Jcenter() with MavenCentral() and it doesn't work
This is the code I use:
final Map<String, dynamic> requestData = {
"email": Encryption().encryptKey(email),
"password": Encryption().encryptKey(password),
"user_ad": userType,
"token_fcm": _tokenFcm,
"is_encrypted": true,
};
Response response = await _dio.post(
"$basePath/login",
data: FormData.fromMap(requestData),
options: Options(
headers: {
"Connection": "keep-alive",
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate, br",
"Host": "btnsmartdev.btn.co.id",
"Content-Type": "application/json",
"Cache-Control": "no-cache",
"Content-Length": "173"
},
validateStatus: (status) {
print("INI STATUS");
print(status);
return (status ?? 0) < 500;
},
followRedirects: false,
)
);
final data = response.data;
Here's what I get in terminal:
Here's the request from postman:
I'm new to Alamofire and now using Alamofire 5. I want to create a POST request with multipart form data, but there's a specific requirement for the JSON body. Here it is:
"item": [
{
"name": "Upload image",
"request": {
"method": "POST",
"header": [],
"body": {
"mode": "formdata",
"formdata": [
{
"key": "files[]",
"type": "file",
"src": []
},
{
"key": "mode",
"value": "public",
"type": "text"
}
]
},
"url": {
"raw": "https://jsonplaceholder.typicode.com/api/image/upload",
"protocol": "https",
"host": [
"jsonplaceholder",
"typicode",
"com"
],
"path": [
"api",
"image",
"upload"
]
}
},
"response": []
},
]
Anyone can help me how to post the data but with multipart form data? Please help.
(It's okay if the POST request is using URLSession)
Whatever I understand from your question and comments, I have created a method from your previous question.
func postImage(images: [UIImage],imgName : [String]) {
var arrFormData = [[String:Any]]()
var imgDataArray: [Data] = []
for image in images {
guard let imgData = image.jpegData(compressionQuality: 0.50) else { return }
imgDataArray.append(imgData)
}
let param1: [String: Any] = [
"key":"files[]",
"type": "file",
"src": imgName
]
let param2: [String: Any] = [
"key": "mode",
"value": "public",
"type": "text"
]
var arrParam = [[String:Any]]()
arrParam.append(param1)
arrParam.append(param2)
arrFormData.append(contentsOf: arrParam)
var param : [String:Any] = [:]
if let theJSONData = try? JSONSerialization.data(
withJSONObject: arrFormData,
options: []) {
let theJSONText = String(data: theJSONData,
encoding: .ascii)
print("JSON string = \(theJSONText!)")
param = ["formData" : theJSONText ?? ""]
}
print(param)
Alamofire.upload(multipartFormData: {
multipartFormData in
for i in 0..<images.count{
if let imageData = images[i].jpegData(compressionQuality: 0.6) {
multipartFormData.append(imageData, withName: "file", fileName: "name.png", mimeType: "image/png")
}
}
for (key, value) in param {
multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
}
}, usingThreshold: 10 * 1024 * 1024,to: apiurl, method: .post, headers: headers, encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON {
response in
print(response.result)
}
case .failure(let encodingError):
print(encodingError)
}
})
}
I am struggling to authenticate using a POST request to an API.
Documentation says that I need to pass in
"Request Headers: Content-Type: application/x-www-form-urlencoded, Request Body: client_id=CLIENT_ID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN."
I cannot get it to work on the iOS app however trying with Postman works fine.
let headers: HTTPHeaders = [
"Contenty-Type": "application/x-www-form-urlencoded"
]
let params = [
"client_id": "123",
"refresh_token": "123"
]
private func getAccess() {
Alamofire.request(getRequest ,method: .post, parameters: params, headers: headers)
.responseJSON { (response) in
switch response.result {
case .success(let json):
print(json)
DispatchQueue.main.async {
}
case .failure(let error):
print(error)
}
}
You are not passing grant_type parameter. Try changing your params dictionary to this:
let params = [
"client_id": "123",
"grant_type": "refresh_token",
"refresh_token": "123"
]
I found some thread the same problem but their answers not works for me.
I have a post request to check user login.
Url form :
"http://support.xxx.xx:8031/serpapi/login/checkLogin"
Parameters :
["contextInfo" :
["clientId": "1000000", "orgId": "1000001",
"warehouseId": "1000002", "roleId": "0"],
"userName": "hanoiaUser", "password": "hanoiaUser"]
Request :
Alamofire.request(url!, method: .post, parameters: params).responseJSON { (response) in
print(response)
}
Error response :
FAILURE: responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}))
Why am i getting this error? and how to solve it ?
Edit : i'm tried with POSTMAN and it return response :
Content-Type : application/json
Body : raw - json
{
"contextInfo" : {
"clientId":1000000,
"orgId": 1000001,
"warehouseId": 1000002,
"roleId": 0
},
"userName": "hanoiaUser",
"password": "hanoiaUser"
}
RESPONSE :
{
"success": true,
"data": [
{
"userId": 1000003,
"userName": "hanoiaUser",
"token": "b7e804d25065e5c3ac97d765180b7986"
}
],
"error": null
}
Ok, finally I solved the problem
Here's new request :
Alamofire.request(url!, method: .post,encoding : JSONEncoding.default, headers: headers, parameters: params).responseJSON { (response) in
print(response)
}
With Headers :
let headers = [
"Content-Type": "application/json"
]
Set the request header like :
request.allHTTPHeaderFields = ["Content-Type":"application/json"]
I'm having hard time doing something simple. The data I want to send is the following:
{
"nickname":"Rado",
"social": {
"data: {
"accesstoken":"xx",
"applicationId":"xx",
"userId":"xx"
},
"type":"whatever"
}
}
Currently I'm doing that:
let params = [
"nickname": userName,
"social": [
"type": "whatever",
"data": [
"userId": accessToken.userID,
"accesstoken": accessToken.tokenString,
"applicationId": accessToken.appID
]
]
]
Alamofire.request(.POST, "url/users", parameters: params, headers: nil)
.responseJSON { response in
}
As a response I get this:
{
"nickname":"Rado",
"social[data][userId]":"xx",
"social[data][applicationId]":"xx",
"social[data][accesstoken]":"xx",
"social[type]":"something"
}
Any advice will be appreciated!
The solution turned out to be really simple. I was missing encoding: .JSON
Alamofire.request(.POST, "url/users", parameters: params, headers: nil, encoding: .JSON)
.responseJSON { response in
}