Swift - 8tracks.com API POST json data fails (422) everytime - objective-c

I'm trying to talk with 8tracks open API in Swift iOS app. I need to make POST authorization request to http://8tracks.com/sessions.jsonwith AFNetworking but everytime I get 422 Unprocessable Entity error..
I tried this endpoint on the web and it works fine. Here is code that I'm using (subclassing AFHTTPSessionManager):
init() {
super.init()
self.responseSerializer = AFJSONResponseSerializer()
self.requestSerializer = AFJSONRequestSerializer()
self.requestSerializer.setValue(API_KEY, forHTTPHeaderField: "X-Api-Key")
self.requestSerializer.setValue("3", forHTTPHeaderField: "X-Api-Version")
}
func login(username: String, password: String, success: (NSURLSessionDataTask!, AnyObject!) -> Void, failure: ((NSURLSessionDataTask!, NSError!) -> Void)?) {
let credentials = ["username": username, "password": password] as Dictionary
self.POST(
API_URL.stringByAppendingString("/sessions.json"),
parameters: credentials,
success: success,
failure: failure
)
}
Error looks as follows:
{ URL: http://8tracks.com/sessions.json } { status code: 422, headers {
"Accept-Ranges" = bytes;
"Access-Control-Allow-Origin" = "*";
Age = 0;
"Cache-Control" = "max-age=0, private, must-revalidate";
Connection = "keep-alive";
"Content-Length" = 125;
"Content-Type" = "application/json; charset=utf-8";
Date = "Wed, 25 Jun 2014 19:29:12 GMT";
Server = "nginx/1.4.3";
Status = "422 Unprocessable Entity";
Via = "1.1 varnish";
"X-Action" = "sessions/create";
"X-Backend" = rails;
"X-Cache" = MISS;
"X-Data-Request" = 1;
"X-Request-Id" = 3040c8bf79936b27075731f634bfd534;
"X-Requests-Left" = 99;
"X-Runtime" = "0.257240";
"X-UA-Compatible" = "IE=Edge,chrome=1";
} }, NSLocalizedDescription=Request failed: client error (422),
NSErrorFailingURLKey=http://8tracks.com/sessions.json}

It might have something to do with subclass AFHTTPSessionManager without a baseURL. I've tested the following code and it works.
let path = "/sessions.json"
let params = ["login": login, "password": password, "api_version": "3"]
let success = {(task: NSURLSessionDataTask!, response: AnyObject!) -> Void in
println(response)
}
let failure = {(task: NSURLSessionDataTask!, error: NSError!) -> Void in
println(error)
}
var client = AFHTTPSessionManager(baseURL: NSURL(string: "https://8tracks.com"))
client.POST(path, parameters: params, success: success, failure: failure)

Related

Multi-part formdata working with Alamofire but failing with URLSession

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

Getting error while uploading image using multipart request in Alamofire

xcode 10.3
swift 4.2
iPhone app
I'm hitting a post type API to upload image along with some string data from a form. I'm getting response result as success but there is an error parameters which indicates: CredStore - performQuery - Error copying matching creds. Error=-25300
I have tried doing some research and found that I've problem with URLCredentialStorage but I don't have any Credentials in API.
I looked at CredStore Perform Query error, I'm having very similar issue but can't find my solution there.
{
let url = route.asURL(constants: constants)
let parameters = route.asParameters(constants: constants)
let headers: HTTPHeaders = [
"authorization-name": APISession.token,
"Content-Type": "multipart/form-data"
]
Log(request: URLRequest(url: url))
Alamofire.upload(multipartFormData: { (multipartFormData) in
for (key, value) in parameters {
if let strValue = value as? String, let valueData = strValue.data(using: .utf8) {
multipartFormData.append(valueData, withName: key)
}
if let imgValue = value as? UIImage, let imgData = imgValue.jpegData(compressionQuality: 0.5) {
multipartFormData.append(imgData, withName: key, mimeType: "image/jpg")
}
}
}, usingThreshold: UInt64.init(), to: url, method: .post, headers: headers) { (result) in
print(result)
switch result{
case .success(let upload, _, _):
upload.uploadProgress(closure: { (progress) in
print("Preogress is: ", progress.fractionCompleted)
})
upload.responseJSON { response in
print("Succesfully uploaded")
switch response.result {
case .success(let value):
print(value)
case .failure(let error):
print(error)
}
}
case .failure(let error):
print("Error in upload: \(error.localizedDescription)")
}
}
}
I'm getting response like this,
success(request: 2019-08-12 13:07:04.224913-0400 project name[65508:460860] CredStore - performQuery - Error copying matching creds. Error=-25300, query={
class = inet;
"m_Limit" = "m_LimitAll";
ptcl = htps;
"r_Attributes" = 1;
sdmn = "url";
srvr = "url";
sync = syna;
}
so I'm confused why I'm getting success response with error parameters in that.
Not sure but I think authorization-name key present in headers is incorrect. It should be Authorization.

Alamofire.download by post with parameters not working

Hello I am doing download file by post with parameters. But server can't receive post parameters.
But if i do same thing with get with url parameters. Everything works fine.
Almofire.request also works fine by post with parameters. But only Almofire.download by post with parameter does not work.
Why Alamofire.download does not send paramters by post method ??
var sourceStringURL : String = "\(tmp_url)download"
let destination: DownloadRequest.DownloadFileDestination =
{
_, _ in
let fileURL = URL(fileURLWithPath: destPath)
return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
}
Alamofire.download(sourceStringURL, method: .post, parameters: ["id": idStr, "var": varStr], encoding: JSONEncoding.default, headers: nil, to: destination)
.downloadProgress
{
progress in
var tmpPercent : Int = Int(progress.fractionCompleted*100 / 1.0)
}
.response
{
response in
if let error = response.error
{
print(error)
}
else
{
//success
}
}
Server receives post request correctly with Retrofit library in Android.
I just found that if i change JSONEncoding.default to URLEncoding.default.
It works fine.

Bad Request: there is no photo in the request

I'm trying to send an image from my application to telegram bot like here
https://newfivefour.com/swift-form-data-multipart-upload-URLRequest.html
Here is the code
let BotToken = "12345"
let ChatID = "123"
func SendToTelegram()
{
var request = URLRequest(url: URL(string: "https://api.telegram.org/bot"+BotToken+"/sendPhoto")!)
request.httpMethod = "POST"
let boundary = "Boundary-\(UUID().uuidString)"
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
let params = [:] as [String: String]
UIGraphicsBeginImageContextWithOptions(ScreenImage.bounds.size, true, 0.0)
ScreenImage.image?.draw(in: CGRect(x: 0, y: 0, width: ScreenImage.frame.size.width, height: ScreenImage.frame.size.height))
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
request.httpBody = createBody(parameters: params,
boundary: boundary,
data: UIImageJPEGRepresentation(image!, 0.7)!,
mimeType: "image/jpg",
filename: "hello.jpg")
print(request.httpBody!)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else { // check for fundamental networking error
return
}
do {
let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? AnyObject
if let parseJSON = json {
print("resp :\(parseJSON)")
}
} catch let error as NSError {
print("error : \(error)")
}
}
task.resume()
}
and get an error
Bad Request: there is no photo in the request";
"error_code" = 400;
ok = 0;
Where do i make a mistake? I'm new in SWIFT and sorry for my English
I know this question is old but the link provided pushed me in the right direction. This is my solution for server side Swift not iOS but you should be able to use it with minimal changes. Remember if you're using iOS, perform none of these operations on the main thread.
class NetworkManager {
func sendTelegramPhoto(_ photo: Data) {
let url = "https://api.telegram.org/bot\(Constants.Telegram.token)/sendPhoto"
let params: [String: Any] = [
"chat_id": Constants.Telegram.uid,
"photo": photo
]
let _ = sendMultiTypePostRequest(url, parameters: params)
}
private func sendMultiTypePostRequest(_ url: String, parameters: [String:String]) -> NetworkResponse {
var networkResponse = NetworkResponse()
let semaphore = DispatchSemaphore(value: 0)
guard let url = URL(string: url) else {
return networkResponse
}
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = "POST"
let boundary = "Boundary-\(UUID().uuidString)"
urlRequest.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
let httpBody = createBody(parameters: parameters,
boundary: boundary,
mimeType: "image/jpeg",
filename: "snapshot.jpg")
let config = URLSessionConfiguration.default
config.requestCachePolicy = .reloadIgnoringLocalCacheData
let session = URLSession(configuration: config)
let task = session.uploadTask(with: urlRequest, from: httpBody) { (data, response, error) in
networkResponse.data = data
networkResponse.response = response
networkResponse.error = error
semaphore.signal()
}
task.resume()
_ = semaphore.wait(timeout: .distantFuture)
return networkResponse
}
private func createBody(parameters: [String: String],
boundary: String,
mimeType: String,
filename: String) -> Data {
var body = Data()
let boundaryPrefix = "--\(boundary)\r\n"
for (key, value) in parameters {
if let data = value as? Data {
body.appendString(boundaryPrefix)
body.appendString("Content-Disposition: form-data; name=\"\(key)\"; filename=\"\(filename)\"\r\n")
body.appendString("Content-Type: \(mimeType)\r\n\r\n")
body.append(data)
body.appendString("\r\n")
} else if let string = value as? String {
body.appendString(boundaryPrefix)
body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
body.appendString("\(string)\r\n")
}
}
body.appendString("--".appending(boundary.appending("--")))
return body
}
}
private extension Data {
mutating func appendString(_ string: String) {
let data = string.data(using: String.Encoding.utf8, allowLossyConversion: false)
append(data!)
}
}

QuickBlox create user issue (bad request) without any error message

I want to create an user using the rest API. Rest API returns an error (bad request), when I made the request. There are not any other error messages.
JSON:
Required Parameters : login, password, email
http://quickblox.com/developers/Users#API_User_Sign_Up
{
"user":
{
"login":"user123456",
"password":"User11#2015",
"email":"xxx#ccc.com.tr",
"blob_id":null,
"external_user_id":null,
"facebook_id":null,
"twitter_id":null,
"full_name":null,
"phone":null,
"website":null,
"custom_data":null,
"tag_list":null
}
}
Rest API Result:
Response Status Code : BadRequest.
Response Content is empty. No error message.
I do not understand the error. Can you help me?
Code :
public NotificationUser CreateUser(string token, NotificationUser notificationUser)
{
var user = new QuickbloxUser()
{
email = notificationUser.Email,
password = notificationUser.Password,
login = notificationUser.Login
};
var jsonBody = JsonConvert.SerializeObject(user);
var request = new RestRequest("users.json", Method.POST);
request.AddHeader("QB-Token", token);
request.AddParameter("user", jsonBody);
var response = _restClient.Execute<RootUser<QuickbloxUserResponse>>(request);
if (response.StatusCode == HttpStatusCode.OK)
{
notificationUser.Id = response.Data.user.id;
notificationUser.Email = response.Data.user.email;
notificationUser.Login = response.Data.user.login;
return notificationUser;
}
return null;
}