How to send a request with alamofire with xml Body

mike vorisis picture mike vorisis · Nov 2, 2016 · Viewed 8.6k times · Source

I installed Alamofire in my project and now here is what I have done.

I installed postman and I put my url and inside body a xml object and I got my result.

Here is a picture of what I exactly have done with postman

enter image description here

How can I now use Alamofire or SWXMLHash to send it as I send it with postman

Thanks in advance!

EDIT

I tried this from another question:

 Alamofire.request(.POST, "https://something.com" , parameters: Dictionary(), encoding: .Custom({
            (convertible, params) in
            let mutableRequest = convertible.URLRequest.copy() as! NSMutableURLRequest

            let data = (self.testString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
            mutableRequest.HTTPBody = data
            return (mutableRequest, nil)
        }))


    .responseJSON { response in


    print(response.response) 

    print(response.result)   


    }
}

But it didn't send anything

This is the log:

Optional( { URL: https://something.com } { status code: 200, headers { Connection = "keep-alive"; "Content-Length" = 349; "Content-Type" = "application/xml"; Date = "Wed, 02 Nov 2016 21:13:32 GMT"; Server = nginx; "Strict-Transport-Security" = "max-age=31536000; includeSubDomains"; } })

FAILURE

EDIT

NEVER FORGET TO PASS parameters if you don't have simple add this , parameters: Dictionary()

Answer

Zeeshan picture Zeeshan · Jun 7, 2017

Using Swift 3 and Alamofire 4

    let stringParams : String = "<msg id=\"123123\" reqTime=\"123123\">" +
        "<params class=\"API\">" + 
        "<param name=\"param1\">123213</param>" + 
        "<param name=\"param2\">1232131</param>" +
        "</params>" +
    "</msg>"

    let url = URL(string:"<#URL#>")
    var xmlRequest = URLRequest(url: url!)
    xmlRequest.httpBody = stringParams.data(using: String.Encoding.utf8, allowLossyConversion: true)
    xmlRequest.httpMethod = "POST"
    xmlRequest.addValue("application/xml", forHTTPHeaderField: "Content-Type")


    Alamofire.request(xmlRequest)
            .responseData { (response) in
                let stringResponse: String = String(data: response.data!, encoding: String.Encoding.utf8) as String!
                debugPrint(stringResponse)
    }