Convert httpBody for x-www-urlencoded - ios

I'm doing a POST call to server but Alamofire always send the body as a JSON and not as a Form URL Encoded, I do know that in oder to encode the body I have to insert data(using: .utf8, allowLossyConversion: false), but I don't know where.
How can I fix my code?
This is my actual code:
func asURLRequest() throws -> URLRequest {
let url = try DBank.StagingServer.baseUrl.asURL()
var urlRequest = URLRequest(url: url.appendingPathComponent(path))
// HTTP Method
urlRequest.httpMethod = method.rawValue
// Common Headers
headers.forEach { (field, value) in
urlRequest.setValue(value, forHTTPHeaderField: field)
}
// Parameters
if let parameters = parameters {
do {
urlRequest.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: [])
} catch {
throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error))
}
}

I'm guessing you have response handler like below:
Alamofire.request(url, method: .post, parameters: params, encoding: URLEncoding(destination: .queryString), headers: headers)
.validate(statusCode: 200..<300)
.responseString { response in
//response.result.value will contain http response from your post call
}
With the result from this response you would set:
UserDefaults.standard.set("<result>", forKey: "<token>")

Related

Backend is unable to find headers when sending request from IOS application

i am able to hit api from postman, but when i hit from IOS application it always throws an error that "A valid API key is required to use this service."
API Endpoint: https://connect.ttfnow.com/api/url/add
Headers: key= "Authorization", value= "Token BDifVxMyHSlB"
Method: POST
Body Raw Json: {url: "www.google.com"}
I used postman code for swift but it did not worked in application.
I tried with url session and alamofire but nothing worked.
let headers: HTTPHeaders = ["Content-Type": "application/json",
"Authorization": "Token BDifVxMyHSlB"]
let params: [String: Any] = ["url": "www.google.com"]
AF.request(URL(string: "https://connect.ttfnow.com/api/url/add")!, method: .post, parameters: params, encoding: JSONEncoding.default, headers: headers).responseJSON { (response) in
print(response)
}
Here is code from url session
var semaphore = DispatchSemaphore (value: 0)
let parameters = "{\n \"url\": \"www.google.com\"\n}"
let postData = parameters.data(using: .utf8)
var request = URLRequest(url: URL(string: "https://connect.ttfnow.com/api/url/add")!,timeoutInterval: Double.infinity)
request.addValue("Token BDifVxMyHSlB", forHTTPHeaderField: "Authorization")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("PHPSESSID=c6mirs7a3qspcq86hhdvo2o2po", forHTTPHeaderField: "Cookie")
request.httpMethod = "POST"
request.httpBody = postData
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data else {
print(String(describing: error))
semaphore.signal()
return
}
print(String(data: data, encoding: .utf8)!)
semaphore.signal()
}
task.resume()
semaphore.wait()
here is image from postman
Header tab of postman

How to set UTF8 encoding for Alamofire POST request body?

I want to send UTF8 encoded JSON body to my REST API. My code right now is
var body : [String:Any]? = ["version":Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""];
.
.
body?["type"] = type
var url : String = UserDefaults.standard.value(forKey:"url") as! String
url.append("MobileLogin")
Alamofire.request(url, method: .post, parameters:body, encoding: JSONEncoding.default, headers: nil).responseJSON { (responseData) in
if((responseData.result.value) != nil) {
.
.
}
}
The problem is that the JSON sent in not UTF8 encoded. Any idea of how to set something like "JSONEncoding.encode("UTF8")" in the Alamofire request?
try this
let options = NSJSONWritingOptions()
let data = try NSJSONSerialization.dataWithJSONObject(parameters!, options: options)
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
mutableURLRequest.HTTPBody = data
or other way
extension String: ParameterEncoding {
public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
var request = try urlRequest.asURLRequest()
request.httpBody = data(using: .utf8, allowLossyConversion: false)
return request
}
}
Alamofire.request(url, method: .post, parameters: [:], encoding: "myBody", headers: [:])

Alamofire 4 Swift 3 ParameterEncoding Custom

I updated my project to Swift 3 and Alamofire 4. I was using custom Encoding, but it's changed to other encoding methods. I am not able to find the alternative/equivalent to this:
alamoFire.request(urlString, method: HTTPMethod.post, parameters: [:], encoding: .Custom({
(convertible, params) in
let mutableRequest = convertible.URLRequest.copy() as! NSMutableURLRequest
let data = (body as NSString).data(using: String.Encoding.utf8)
mutableRequest.httpBody = data
return (mutableRequest, nil)
}), headers: headers()).responseJSON { (responseObject) -> Void in
switch responseObject.result {
case .success(let JSON):
success(responseObject: JSON)
case .failure(let error):
failure(error: responseObject)
}
}
I also tried by making URLRequest object and simple request its also giving me errors
var request = URLRequest(url: URL(string: urlString)!)
let data = (body as NSString).data(using: String.Encoding.utf8.rawValue)
request.httpBody = data
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers()
alamoFire.request(request).responseJSON { (responseObject) -> Void in
switch responseObject.result {
case .success(let JSON):
success(JSON)
case .failure(let error):
failure(responseObject, error)
}
}
Do point me in some direction, how to attach httpbody with the Alamofire 4
Try this method?
Alamofire.request(url, method: HTTPMethod.post, parameters: parameters, encoding: URLEncoding.httpBody, headers: nil).responseObject(completionHandler: { (response : DataResponse<T>) in
})
In Alamofire 4.0 you should use ParameterEncoding protocol. Here is an example, which makes any String UTF8 encodable.
extension String: ParameterEncoding {
public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
var request = try urlRequest.asURLRequest()
request.httpBody = data(using: .utf8, allowLossyConversion: false)
return request
}
}
Alamofire.request("http://mywebsite.com/post-request", method: .post, parameters: [:], encoding: "myBody", headers: [:])

Why Authorization header gets removed in iOS PATCH requests?

there. I got a very strange problem. The thing is that when i'm trying to send PATCH requests server says that no Authorization header contains token. The same for PUT request.Tried to sniff and found out that no Authorization header is sent at all. While any other types of request contain Authorization header. First thought its Alamofire framework specific problem, but using NSURLConnection requests and NSURLSession tasks gave me the same: NO AUTHORIZATION HEADER IS SENT!
Here is my code used for Alamofire:
Alamofire.request(.PATCH, path, parameters: ["email":"new#mail.com"], encoding: .JSON, headers: ["Authorization":"token \ ((User.sharedUser().token)!)"]).validate().responseJSON { (response) in
if response.response?.statusCode == 200{
print("success")
}else{
print("Error")
}
}
and here is code with NSURLConnection:
let request:NSMutableURLRequest = NSMutableURLRequest(URL:url)
request.HTTPMethod = "PATCH"
request.addValue("\(token)", forHTTPHeaderField: "authorization")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
do{
let bodyData = try NSJSONSerialization.dataWithJSONObject(["email":"nuv#gmail.com"], options: [])
request.HTTPBody = bodyData
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue())
{
(response, data, error) in
if let mdata = data {
let contents = NSString(data:data, encoding:NSUTF8StringEncoding)
print(contents)
} else {
print(error?.localizedDescription)
}
}
}catch{
print("failed serialization")
}
IIRC, the Authorization header is one of those headers that NSURLSession reserves for its own purposes, and may overwrite with its own values—particularly if you're sending something that looks like normal HTTP authentication.
Can you send an X-Authorization header instead?
Anyone who is looking for Alamofire 5(AF 5) solution here's the solution:
let headers: [String:String] = [...]
let params: [String: Any] = [...]
let url = URL(...)
let redirector = Redirector(behavior: Redirector.Behavior.modify({ (task, urlRequest, resp) in
var urlRequest = urlRequest
headers.forEach { header in
urlRequest.addValue(header.value, forHTTPHeaderField: header.key)
}
return urlRequest
}))
//use desired request func of alamofire and your desired enconding
AF.request(url, method: .post, parameters: params, encoding: JSONEncoding.default, headers: headers)
.responseJSON { response in
//handleDataResponse...
}.redirect(using: redirector)

POST request with a simple string in body with Alamofire

how is it possible to send a POST request with a simple string in the HTTP body with Alamofire in my iOS app?
As default Alamofire needs parameters for a request:
Alamofire.request(.POST, "http://mywebsite.example/post-request", parameters: ["foo": "bar"])
These parameters contain key-value-pairs. But I don't want to send a request with a key-value string in the HTTP body.
I mean something like this:
Alamofire.request(.POST, "http://mywebsite.example/post-request", body: "myBodyString")
Your example Alamofire.request(.POST, "http://mywebsite.example/post-request", parameters: ["foo": "bar"]) already contains "foo=bar" string as its body.
But if you really want string with custom format. You can do this:
Alamofire.request(.POST, "http://mywebsite.example/post-request", parameters: [:], encoding: .Custom({
(convertible, params) in
var mutableRequest = convertible.URLRequest.copy() as NSMutableURLRequest
mutableRequest.HTTPBody = "myBodyString".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
return (mutableRequest, nil)
}))
Note: parameters should not be nil
UPDATE (Alamofire 4.0, Swift 3.0):
In Alamofire 4.0 API has changed. So for custom encoding we need value/object which conforms to ParameterEncoding protocol.
extension String: ParameterEncoding {
public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
var request = try urlRequest.asURLRequest()
request.httpBody = data(using: .utf8, allowLossyConversion: false)
return request
}
}
Alamofire.request("http://mywebsite.example/post-request", method: .post, parameters: [:], encoding: "myBody", headers: [:])
You can do this:
I created a separated request Alamofire object.
Convert string to Data
Put in httpBody the data
var request = URLRequest(url: URL(string: url)!)
request.httpMethod = HTTPMethod.post.rawValue
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let pjson = attendences.toJSONString(prettyPrint: false)
let data = (pjson?.data(using: .utf8))! as Data
request.httpBody = data
Alamofire.request(request).responseJSON { (response) in
print(response)
}
If you use Alamofire, it is enough to set encoding type to URLEncoding.httpBody
With that, you can send your data as a string in the httpbody although you defined it as json in your code.
It worked for me..
Updated for Badr Filali's question:
var url = "http://..."
let _headers : HTTPHeaders = ["Content-Type":"application/x-www-form-urlencoded"]
let params : Parameters = ["grant_type":"password","username":"mail","password":"pass"]
let url = NSURL(string:"url" as String)
request(url, method: .post, parameters: params, encoding: URLEncoding.httpBody, headers: _headers).responseJSON(
completionHandler: { response in response
let jsonResponse = response.result.value as! NSDictionary
if jsonResponse["access_token"] != nil
{
access_token = String(describing: jsonResponse["accesstoken"]!)
}
})
I modified #Silmaril's answer to extend Alamofire's Manager.
This solution uses EVReflection to serialize an object directly:
//Extend Alamofire so it can do POSTs with a JSON body from passed object
extension Alamofire.Manager {
public class func request(
method: Alamofire.Method,
_ URLString: URLStringConvertible,
bodyObject: EVObject)
-> Request
{
return Manager.sharedInstance.request(
method,
URLString,
parameters: [:],
encoding: .Custom({ (convertible, params) in
let mutableRequest = convertible.URLRequest.copy() as! NSMutableURLRequest
mutableRequest.HTTPBody = bodyObject.toJsonString().dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
return (mutableRequest, nil)
})
)
}
}
Then you can use it like this:
Alamofire.Manager.request(.POST, endpointUrlString, bodyObject: myObjectToPost)
Based on Illya Krit's answer
Details
Xcode Version 10.2.1 (10E1001)
Swift 5
Alamofire 4.8.2
Solution
import Alamofire
struct BodyStringEncoding: ParameterEncoding {
private let body: String
init(body: String) { self.body = body }
func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
guard var urlRequest = urlRequest.urlRequest else { throw Errors.emptyURLRequest }
guard let data = body.data(using: .utf8) else { throw Errors.encodingProblem }
urlRequest.httpBody = data
return urlRequest
}
}
extension BodyStringEncoding {
enum Errors: Error {
case emptyURLRequest
case encodingProblem
}
}
extension BodyStringEncoding.Errors: LocalizedError {
var errorDescription: String? {
switch self {
case .emptyURLRequest: return "Empty url request"
case .encodingProblem: return "Encoding problem"
}
}
}
Usage
Alamofire.request(url, method: .post, parameters: nil, encoding: BodyStringEncoding(body: text), headers: headers).responseJSON { response in
print(response)
}
If you want to post string as raw body in request
return Alamofire.request(.POST, "http://mywebsite.com/post-request" , parameters: [:], encoding: .Custom({
(convertible, params) in
let mutableRequest = convertible.URLRequest.copy() as! NSMutableURLRequest
let data = ("myBodyString" as NSString).dataUsingEncoding(NSUTF8StringEncoding)
mutableRequest.HTTPBody = data
return (mutableRequest, nil)
}))
I have done it for array from strings. This solution is adjusted for string in body.
The "native" way from Alamofire 4:
struct JSONStringArrayEncoding: ParameterEncoding {
private let myString: String
init(string: String) {
self.myString = string
}
func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
var urlRequest = urlRequest.urlRequest
let data = myString.data(using: .utf8)!
if urlRequest?.value(forHTTPHeaderField: "Content-Type") == nil {
urlRequest?.setValue("application/json", forHTTPHeaderField: "Content-Type")
}
urlRequest?.httpBody = data
return urlRequest!
}
}
And then make your request with:
Alamofire.request("your url string", method: .post, parameters: [:], encoding: JSONStringArrayEncoding.init(string: "My string for body"), headers: [:])
I've used answer of #afrodev as reference. In my case I take parameter to my function as string that have to be posted in request. So, here is the code:
func defineOriginalLanguage(ofText: String) {
let text = ofText
let stringURL = basicURL + "identify?version=2018-05-01"
let url = URL(string: stringURL)
var request = URLRequest(url: url!)
request.httpMethod = HTTPMethod.post.rawValue
request.setValue("text/plain", forHTTPHeaderField: "Content-Type")
request.httpBody = text.data(using: .utf8)
Alamofire.request(request)
.responseJSON { response in
print(response)
}
}
func paramsFromJSON(json: String) -> [String : AnyObject]?
{
let objectData: NSData = (json.dataUsingEncoding(NSUTF8StringEncoding))!
var jsonDict: [ String : AnyObject]!
do {
jsonDict = try NSJSONSerialization.JSONObjectWithData(objectData, options: .MutableContainers) as! [ String : AnyObject]
return jsonDict
} catch {
print("JSON serialization failed: \(error)")
return nil
}
}
let json = Mapper().toJSONString(loginJSON, prettyPrint: false)
Alamofire.request(.POST, url + "/login", parameters: paramsFromJSON(json!), encoding: .JSON)
My case, posting alamofire with content-type: "Content-Type":"application/x-www-form-urlencoded", I had to change encoding of alampfire post request
from : JSONENCODING.DEFAULT
to: URLEncoding.httpBody
here:
let url = ServicesURls.register_token()
let body = [
"UserName": "Minus28",
"grant_type": "password",
"Password": "1a29fcd1-2adb-4eaa-9abf-b86607f87085",
"DeviceNumber": "e9c156d2ab5421e5",
"AppNotificationKey": "test-test-test",
"RegistrationEmail": email,
"RegistrationPassword": password,
"RegistrationType": 2
] as [String : Any]
Alamofire.request(url, method: .post, parameters: body, encoding: URLEncoding.httpBody , headers: setUpHeaders()).log().responseJSON { (response) in
let parameters = ["foo": "bar"]
// 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))
Xcode 8.X , Swift 3.X
Easy Use;
let params:NSMutableDictionary? = ["foo": "bar"];
let ulr = NSURL(string:"http://mywebsite.com/post-request" as String)
let request = NSMutableURLRequest(url: ulr! as URL)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let data = try! JSONSerialization.data(withJSONObject: params!, options: JSONSerialization.WritingOptions.prettyPrinted)
let json = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
if let json = json {
print(json)
}
request.httpBody = json!.data(using: String.Encoding.utf8.rawValue);
Alamofire.request(request as! URLRequestConvertible)
.responseJSON { response in
// do whatever you want here
print(response.request)
print(response.response)
print(response.data)
print(response.result)
}

Resources