ios json swift - POST request with a simple string in body with Alamofire

4 Answers

You can do this:

  1. I created a separated request Alamofire object.
  2. Convert string to Data
  3. Put in httpBody the data

    var request = URLRequest(url: URL(string: url)!)
    request.httpMethod =
    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

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, "", 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, "", body: "myBodyString")

If you use Alamofire, it is enough to encoding type to "URLEncoding.httpBody"

With that, you can send your data as a string in the httpbody allthough you defined it json in your code.

It worked for me..


  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"]!)



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)

Xcode 8.X , Swift 3.X

Easy Use;

 let params:NSMutableDictionary? = ["foo": "bar"];
            let ulr =  NSURL(string:"" as String)
            let request = NSMutableURLRequest(url: ulr! as URL)
            request.httpMethod = "POST"
            request.setValue("application/json", forHTTPHeaderField: "Content-Type")
            let data = try! params!, options: JSONSerialization.WritingOptions.prettyPrinted)

            let json = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
            if let json = json {
            request.httpBody = json!.data(using: String.Encoding.utf8.rawValue);

            Alamofire.request(request as! URLRequestConvertible)
                .responseJSON { response in
                    // do whatever you want here