Hey guys I am trying to use the face API to detect human body in a picture, but I keep getting 400 bad request. I think there is something wrong with my request code, but I am not sure where. For test, I host a picture on a third-party website just want to know how to get the request right. I will delete the api key later in case someone use it improperly.
private func requestFacePlusAPI() {
let url = URL(string: "https://api-cn.faceplusplus.com/humanbodypp/v1/detect")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("multipart/form-data", forHTTPHeaderField: "Content-type")
let api_key = "TpDqYnF1c5xe_iQzaBkVGkAqflqS3aCP"
let api_secret = "JsDx4hiQUOSXuus8MV21WB4F5YzQnB4B"
guard model.ImageData != nil else { return }
let image_base64 = model.ImageData!.base64EncodedData()
print(model.ImageData!)
print(image_base64)
let data = FacePlusData(api_key: api_key, api_secret: api_secret, image_url: "https://i.postimg.cc/prz1VKTY/Wechat-IMG2.jpg")
guard let uploadData = try? JSONEncoder().encode(data) else {
return
}
let task = URLSession.shared.uploadTask(with: request, from: uploadData) { data, response, error in
if let error = error {
print ("error: \(error)")
return
}
guard let response = response as? HTTPURLResponse,
(200...299).contains(response.statusCode) else {
print (response)
print ("server error")
return
}
if let mimeType = response.mimeType,
mimeType == "application/json",
let data = data,
let dataString = String(data: data, encoding: .utf8) {
print ("got data: \(dataString)")
}
}
task.resume()
}
CodePudding user response:
Seeing the documentation and the cURL sample:
curl -X POST "https://api-us.faceplusplus.com/humanbodypp/beta/detect" -F "api_key=<api_key>" \
-F "api_secret=<api_secret>" \
-F "image_file=@image_file.jpg" \
-F "return_attributes=gender"
You need to send parameters in "URL Encoded Form":
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-type")
...
let uploadData = Data("api_key=\(api_key)&api_secret=\(api_secret)&image_url=https://i.postimg.cc/prz1VKTY/Wechat-IMG2.jpg".utf8)