Alamofire POST Bad Request - ios

I'm trying to make a post request to my server through Alamofire but it returns a bad request saying that parameters are badly formed. Same requests is working in postman and swagger.
Here is the code:
var params = [
"username": "jora#company.com",
"password": "test123",
"pushToken": "No token"
]
Alamofire.request("https://thankyouposta.com/api/auth", method: .post, parameters: params, encoding: URLEncoding.default, headers: R.Api.headers).responseJSON { response in
switch response.result {
case .success(let value):
// ...
case .failure(let error):
// ...
}
}
Update 1
Parameters needs to be sent as form url encoded body
Update 2
Value of R.Api.headers is
["Content-Type" : "application/x-www-form-urlencoded"]

If you want to send request as a form-urlencoded, you should put it as a headers and change your encoding:
let headers = [
"Content-Type": "application/x-www-form-urlencoded"
]
var params = [
"username": "jora#company.com",
"password": "test123",
"pushToken": "No token"
]
Alamofire.request("your_url_here", method: .post, parameters: parameters, encoding: URLEncoding.httpBody, headers: headers).responseJSON { response in
}

The backend was an IIS server with redirection to Tomcat. I've excluded IIS and make the requests directly to Tomcat and it is working now. As I understood, the problem was in delivering the request from IIS to Tomcat.
Solved

Related

Getting bad request error in FedEx OAuth Swift

I am trying to authorised FedEx token but getting 400 error.
FedEx Developer link : https://developer.fedex.com/api/en-us/catalog/authorization/v1/docs.html#operation/API%20Authorization
Code Snippet :
let headers = [
"Content-Type": "application/x-www-form-urlencoded"
]
let parameters = [
"grant_type":"client_credentials",
"client_id":"***********************",
"client_secret":"***********************"
] as [String : Any]
Alamofire.request("https://apis-sandbox.fedex.com/oauth/token", method: .post, parameters:parameters,encoding: JSONEncoding.default, headers: headers).responseJSON {
response in
switch response.result {
case .success:
print(response)
break
case .failure(let error):
print(error)
}
}
Getting Error :
{
errors = (
{
code = "BAD.REQUEST.ERROR";
message = "Missing or duplicate parameters. Please modify your request and try again.";
}
);
transactionId = "b1d9d540-ed29-49fd-a4c2-907718e918c2";
}
From the FedEx documentation you can see that the parameters need to be sent as form-urlencoded.
And indeed, you have specified this in your headers, but then you have used a JSON encoder, so a JSON document will be sent.
Rather, use
Alamofire.request("https://apis-sandbox.fedex.com/oauth/token",method: .post, parameters: parameters, encoder: URLEncoding.default, headers: headers)

Alamofire 4 missing parameters in POST

Spent hours on this with no success.
I'm using Alamofire to make a HTTP POST to back end server which requires some parameters to be supplied with request.
I'm successfully hitting the server but the server is responding with a 500 stating no parameters were sent?
I've tried most of the SO solutions (changing the encoding type, setting parameters as NSDict, etc) but with no success.
Any help greatly appreciated.
PS its Swift3 with Alamofire 4
Code:
let params: [String: String] = ["deviceID": "Some device ID",
"email": "email","password": "password","userid": "1234",
"username":"gordon"]
let request_params: Parameters = ["LoginUser" : params]
let url = "https://myserver/LogIn" as String
Alamofire.request(url, method: .post, parameters: request_params, encoding: URLEncoding.default, headers: [
"Content-Type": "application/x-www-form-urlencoded"
]).responseString { (response:DataResponse<String>) in
switch(response.result) {
case.success(let data):
print("success",data)
print(response.response)
case.failure(let error):
print("Failed!",error)
}
}
Update:
Below is the body of the POST, it looks like this is where the problem exists:
Alamofire POST body (from above code) -
(LoginUser%5BdeviceID%5D=12345&LoginUser%5Bemail%5D=gordon%40test.com&LoginUser%5Buserid%5D=00000000-0000-0000-0000-000000000000&LoginUser%5Bpassword%5D=testPassword&LoginUser%5Busername%5D=gordon)
It should be something like (ignoring the encoding values):
This is a functional post body-
LoginUser=%7B%22deviceID%22%3A%22%22%2C%22email%22%3A%22gordon%40test.com%22%2C%22password%22%3A%22testPassword%22%2C%22userid%22%3A%2200000000-0000-0000-0000-000000000000%22%2C%22username%22%3A%22gordon%22%7D
As you can see the Alamofire post seems to concatenate the LoginUser to start of each attribute? Also missing the LoginUser= at start??
Try to use JSONEncoding.default instead of URLEncoding.default
OK so I got this working with the below code, would be very interested in understanding if this is the most efficient means of posting param?
let params: NSMutableDictionary? = ["deviceID": "someDeviceID",
"email": "emailAddress","password": "aSecret","userid": "12345",
"username":"gordon"]
let url = "https://serverAdrress" as String
let data = try! JSONSerialization.data(withJSONObject: params!, options: JSONSerialization.WritingOptions.prettyPrinted)
let json: NSString! = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
let request_params: Parameters = ["LoginUser" : json as Any]
Alamofire.request(url, method: .post, parameters: request_params, encoding: URLEncoding.httpBody, headers: [
"Content-Type": "application/x-www-form-urlencoded"
]).responseString { (response:DataResponse<String>) in
switch(response.result) {
case.success(let data):
print("success",data)
print(NSString(data: (response.request?.httpBody)!, encoding: String.Encoding.utf8.rawValue))
print(response.response)
case.failure(let error):
print("Not Success",error)
}
}

Swift Alamofire Getting Token from Refresh Token Request Error

I'm pretty new to using Alamofire, and I am banging my head against the wall with this request. I'm using GIDSignIn, and successfully get a token and refresh token for the user, with the scope ["https://www.googleapis.com/auth/youtube.readonly"].
I'm trying to complete this request, as shown as an example on the site. The site says to ignore using client_secret for iOS, which I do.
POST /oauth2/v4/token HTTP/1.1
Host: www.googleapis.com
Content-Type: application/x-www-form-urlencoded
client_id=<your_client_id>&
client_secret=<your_client_secret>&
refresh_token=<refresh_token>&
grant_type=refresh_token
Below is how I've implemented it with Alamofire. My client_id is the value from the CLIENT_ID key in the GoogleService-Info.Plist, a string ending in .apps.googleusercontent.com. The refresh_token also seems to have the right format from other examples I've seen online.
let endpoint = "https://www.googleapis.com/oauth2/v4/token"
let parameters = [
"client_id" : client_id,
"refresh_token" : refresh_token,
"grant_type" : "refresh_token"
]
Alamofire.request(endpoint, method: .post,
parameters: parameters,
encoding: JSONEncoding.default)
.responseJSON { (data) in
print("data: \(data)")
let json = JSON(data.result)
}
The data response is
data: SUCCESS: {
error = "unsupported_grant_type";
"error_description" = "Invalid grant_type: ";
}
Not terribly successful. Do I need to configure my request differently, or get appropriate access / permission to get the token? Thank you so much!
#BikeshThakur helped me figure it out! The URLEncoding.httpBody did the trick! I don't need any headers either.
Alamofire.request(endpoint, method: .post,
parameters: parameters,
encoding: URLEncoding.httpBody)
i have tired in my code like this way , you also need to check sometime encoding type URLEncoding.httpBody hope it may help
let headers = [
"Content-Type": "application/x-www-form-urlencoded"
]
Alamofire.request("https://accounts.google.com/o/oauth2/revoke?token={\(token)}", method: .post, parameters: parameters, encoding: URLEncoding.httpBody, headers: headers).responseJSON { (response:DataResponse<Any>) in

Alamofire 4.3 can't send JSON request

Iam Trying to send a JSON request using Alamofire but it's not working as a JSON Request here's my JSON :
{"ClientID":"55050","AdminId":"myemail","Password":"123"}
content-type → application/json; charset=utf-8
and here's my code :
import Alamofire
func doLogin(username:String ,password:String) {
let parameters = ["ClientID":"55050" , "AdminId":username,"Password":password]
Alamofire.request("myurl.com", method: .post, parameters: parameters, encoding: JSONEncoding(options: []) ).responseJSON(completionHandler: {
response in
print(response)
})
and here's the response which i am getting
FAILURE: responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 3." UserInfo={NSDebugDescription=Invalid value around character 3.}))
By reading the documentation i just need to put header to set the request as application/json
so i added extra parameter header :
let headers: HTTPHeaders = [
"Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
"Accept": "application/json"
]
Alamofire.request(ApiKeys().login, method : .post , parameters : parameters, encoding: JSONEncoding.default , headers: headers).responseJSON { response in
}
and now it's working perfectly thanks everyone for trying to help :)
It seems you must have missed header in your request. So, there has been no response.
Your header must be a dictionary [String: String].
let header = ["Content-Type" : "application/json"]
And your sample request should be:
Alamofire.request(getCategoryPath, method: .post, parameters: parameters, encoding: URLEncoding.default, headers: header)
.responseJSON { response in
guard response.result.error == nil else {
print(response.result.error!)
}
print(response.result.value)
}

Twitter API in SWIFT via Alamofire

I currently try to send a simple query - in Postman it works fine for me, but in SWIFT I simply cant get it working
My Code looks like:
func TWITTER_getPosts(username:String){
let headers = [
"screen_name": "username",
"authorization": "OAuth oauth_consumer_key=\"<KEY>\",oauth_token=\"<KEY>\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"1469246792\",oauth_nonce=\"n6Sxbq\",oauth_version=\"1.0\",oauth_signature=\"<KEY>\"",
"include_rts": "false"
]
Alamofire.request(.GET, "https://api.twitter.com/1.1/statuses/user_timeline.json", parameters: headers)
.responseJSON { response in
print(response.request) // original URL request
print(response.response) // URL response
print(response.data) // server data
print(response.result) // result of response serialization
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
}
}
I Always end in a
errors = (
{
code = 215;
message = "Bad Authentication data.";
One of the parameters for the request method is incorrect.
If you are passing headers, they shouldn't be passed in parameters, they should be passed as the following:
let headers = [
"Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
"Accept": "application/json"
]
Alamofire.request(.GET, "https://httpbin.org/get", headers: headers)
.responseJSON { response in
debugPrint(response)
}
headers: headers should be the way to go.

Resources