Swift 3 Alamofire print JSON body send to server - ios

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!

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

Alamofire/Swift - How to add a boolean header value in request

I want to create a request in Alamofire with headers with boolean values, but the HTTPHeaders just accept a dictionary [String:String].
What do I do?
Example of header that what I need:
static let headers: HTTPHeaders = [
"Content-Type":"application/json",
"boolValue": true
]
To response this,
I create a HTTPHeaders [String:String] like this:
static let headers: HTTPHeaders = [
"Content-Type":"application/json",
"boolValue": "true"
]
I changed my Alamofire request encoder from URLEncoding.default to JSONEncoding.default like this:
let req = Alamofire.request(url, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: header)
This happens because Alamofire on URLEnconding no convert the dictionary [String:String] to primitive values and JSONEncoding does.

Pass parameter with json field when invoking POST in Alamofire

I have encountered an issue in swift 3:
I have an API which I need to access for data in my app, but the parameter that it demands is in the following format:
"jsonRequest" = {
"header" : "GetLocationListReq",
"accessKey" : "1234567890abcdefghij"
}//this is in json format.
I tried to pass this parameter as dictionary to call the API, but at that point I obtained this message error:
Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed
Any one knows how I can solve the problem?
I think you want to pass these things in header of the request.
for that you need to do like this
let headers = ["header": "GetLocationListReq",
"accessKey": "1234567890abcdefghij"]
Alamofire.request(url, method: .post, parameters: nil, encoding: JSONEncoding.default, headers: headers).responseJSON{
r in
//do what you want here
}
hope this will work.
try to post this code
let par:[String:Any] = ["jsonRequest":[
"header" : "GetLocationListReq",
"accessKey" : "1234567890abcdefghij"
]]
pass it like that in Alamofire
Alamofire.request(url, method: .post, parameters: par, encoding: JSONEncoding.default, headers: nil).responseJSON{
r in
//do what you want here
}

post application/x-www-form-urlencoded Alamofire

I want to use Alamofire to retrieve a bearer token from Web API but I am new to ios and alamofire. How can I accomplish this with Alamofire?
func executeURLEncodedRequest(url: URL, model: [String : String]?, handler: RequestHandlerProtocol) {
addAuthorizationHeader()
Alamofire.request(.POST,createUrl(url), parameters: model, headers: headers,encoding:.Json)
}
Well you don't really need Alamofire to do this (it can be simply done using a plain NSURLRequest) but here goes:
let headers = [
"Content-Type": "application/x-www-form-urlencoded"
]
let parameters = [
"myParameter": "value"
]
let url = NSURL(string: "https://something.com")!
Alamofire.request(.POST, url, parameters: parameters, headers: headers, encoding: .URLEncodedInURL).response { request, response, data, error in
print(request)
print(response)
print(data)
print(error)
}
I think that the headers can be omitted since alamofire will append the appropriate Content-Type header. Let me know if it works.
You can also find a ton of specification with examples here.
Alamofire 4.7.3 and Swift 4.0 above
As per the documentation for POST Request With URL-Encoded Parameters
let parameters: Parameters = [
"foo": "bar",
"val": 1
]
// All three of these calls are equivalent
Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters)
Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: URLEncoding.default)
Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: URLEncoding.httpBody)
// HTTP body: foo=bar&val=1
Alamofire 5.2
let parameters: [String: [String]] = [
"foo": ["bar"],
"baz": ["a", "b"],
"qux": ["x", "y", "z"]
]
// All three of these calls are equivalent
AF.request("https://httpbin.org/post", method: .post, parameters: parameters)
AF.request("https://httpbin.org/post", method: .post, parameters: parameters, encoder: URLEncodedFormParameterEncoder.default)
AF.request("https://httpbin.org/post", method: .post, parameters: parameters, encoder: URLEncodedFormParameterEncoder(destination: .httpBody))
// HTTP body: "qux[]=x&qux[]=y&qux[]=z&baz[]=a&baz[]=b&foo[]=bar"
Here is example code that should work with Alamofire 4.x and Swift 3.x as of August 2017:
let parameters = [
"myParameter": "value"
]
Alamofire.request("https://something.com", method: .post, parameters: parameters, encoding: URLEncoding()).response { response in
print(response.request)
print(response.response)
print(response.data)
print(response.error)
}
There is no need to set the content-type header explicitly, as it is set by Alamofire automatically.

alamofire header + parameters

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

Resources