alamofire header + parameters - ios

Hello World,
I come to you because, I try to send headers with parameters in the same function like this:
Alamofire.Manager.sharedInstance.request(.PUT, "url", headers: headers, parameters: parameters)
but maybe you already knew just headers are sent.
I tried also this way:
let manager = Alamofire.Manager.sharedInstance
manager.session.configuration.HTTPAdditionalHeaders = [
"Authorization": token]
manager.request(.PUT, "http://192.168.99.100:3030/users/\(identity)", parameters: parameters, encoding:.JSON)
but the headers are not sent..
What is the easy way to implement headers in alamofire?
Thanks by advance ;-)
regards,

set headers in dictionary just like other parameter and pass it in headers. for example
let Auth_header = [ "Authorization" : token ]
Alamofire.Manager.sharedInstance.request(.PUT, "url", headers: Auth_header, parameters: parameters)
You can check details HTTP Basic Authentication
HTTP Basic Authentication
The authenticate method on a Request will automatically provide an NSURLCredential to an NSURLAuthenticationChallenge when appropriate:
let user = "user"
let password = "password"
Alamofire.request(.GET, "https://httpbin.org/basic-auth/\(user)/\(password)")
.authenticate(user: user, password: password)
.responseJSON { response in
debugPrint(response)
}
Depending upon your server implementation, an Authorization header may also be appropriate:
let user = "user"
let password = "password"
let credentialData = "\(user):\(password)".dataUsingEncoding(NSUTF8StringEncoding)!
let base64Credentials = credentialData.base64EncodedStringWithOptions([])
let headers = ["Authorization": "Basic \(base64Credentials)"]
Alamofire.request(.GET, "https://httpbin.org/basic-auth/user/password", headers: headers)
.responseJSON { response in
debugPrint(response)
}

I already did what you said in the first comment but anyway there are just the headers sent:
let parameters : [String : NSString] = [
"username": username,
"email": email,
"currentPassword": currentpassword,
"newPassword": newpassword]
let Auth_header = [ "Authorization" : token ]
Alamofire.Manager.sharedInstance.request(.PUT, "url", headers: Auth_header, parameters: parameters)
Resolved: The probleme was that I did't give the encoding in parameter
Alamofire.Manager.sharedInstance.request(.PUT, "url", headers: Auth_header, parameters: parameters, encoding: .JSON)
Thanks to EI Captain

Related

Alamofire POST Bad Request

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

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

{ error = "invalid_request"; "error_description" = "Required parameter is missing: grant_type"; } In swift

I am trying with this but every time I will get
{ error = "invalid_request"; "error_description" = "Required parameter is missing: grant_type"; }
Request String:
let headers = [ "Content-Type" : "application/x-www-form-urlencoded"]
let urlString = "https://accounts.google.com/o/oauth2/token?"
Alamofire.request(urlString, method: .post, parameters: ["grant_type":"authorization_code","code":"4/FAOYR1mQo1lN1Gdg9jDnigwZ8RP76NUrqPbYZlMCSP28","client_id":"387376833747-12pbtud9tepr4di0insdhc0d4qpf5e9m.apps.googleusercontent.com","client_secret":"xOacVhLavM9fH8SpOK4I2dRJ","redirect_uri":"https://stackoverflow.com"], encoding: JSONEncoding.default, headers : headers)
.responseJSON { response in
print(response)
print(response.result)
}
Also try with passing request parameter like this but still doesn't work for me.
You can't send appended parameter with url while post request.
Pass parameter as below this
let headers = [ "Content-Type" : "application/x-www-form-urlencoded","grant_type" : "authorization_code"" ]
let urlString = "https://accounts.google.com/o/oauth2/token?"
Alamofire.request(urlString, method: .post, parameters: ["code":"4/FAOYR1mQo1lN1Gdg9jDnigwZ8RP76NUrqPbYZlMCSP28","client_id":"apps.googleusercontent.com","client_secret":"","redirect_uri":"https://stackoverflow.com"], encoding: JSONEncoding.default, headers : headers)
.responseJSON { response in
print(response)
print(response.result)
}
These error invalid_request occurs only below cases so please check with your server side what is missing or invalid.
The request is missing a required parameter, includes an unsupported
or invalid parameter value, repeats a parameter,includes multiple
credentials, utilizes more than one mechanism for authenticating the
client, or is otherwise malformed.

Swift 3 Alamofire print JSON body send to server

I use Alamofire to send requests in my iOS App. For debugging, i want to see what the JSON Body looks like in raw. I expect it to look like:
{"receiverUserGroups":["testgroup"],"message":"testmessage"}
But I have not found a way to print it out in that format. I simply define the header and the params and make a request.
let headers: HTTPHeaders = [
"sid": sid,
"Content-Type": "application/json"
]
var params = [
"receiverUserGroups":[""],
"message": "testmessage"] as [String : Any]
params["receiverUserGroups"] = group
Alamofire.request(urlString, method: .post, parameters: params, encoding: JSONEncoding.default, headers: headers)
Is there a way to see what i am sending to the server? Thank you in advance!

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