POST request with a simple string in the enclosure with Alamofire

how can I send a POST request with a simple string in the body of HTTP using Alamofire in my iOS application?

By default, Alamofire needs parameters for the request:

Alamofire.request(.POST, "http://mywebsite.com/post-request", parameters: ["foo": "bar"]) 

These parameters contain key-value pairs. But I do not want to send the request using the key string to the HTTP body.

I mean something like this:

 Alamofire.request(.POST, "http://mywebsite.com/post-request", body: "myBodyString") 
+74
ios swift request alamofire
Jan 09 '15 at 6:53
source share
10 answers

In your example, Alamofire.request(.POST, "http://mywebsite.com/post-request", parameters: ["foo": "bar"]) already contains the string "foo = bar" as its body. But if you really need a custom format string. You can do it:

 Alamofire.request(.POST, "http://mywebsite.com/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 must not be nil

UPDATE (Alamofire 4.0, Swift 3.0):

In Alamofire 4.0, the API has changed. Therefore, for custom coding, we need a value / object that conforms to the 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.com/post-request", method: .post, parameters: [:], encoding: "myBody", headers: [:]) 
+82
Feb 16 '15 at 23:32
source share

You can do it:

  • I created a separate Alamofire request object.
  • Convert string to data
  • Enter httpBody 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) } 
+50
Feb 10 '17 at 14:45
source share

If you use Alamofire, just enter the encoding type in "URLEncoding.httpBody"

With this, you can send your data as a string in httpbody, although you defined it json in your code.

It worked for me ..

UPDATED for

  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"]!) } }) 
+11
Dec 25 '16 at 13:34
source share

I changed @Silmaril's response to the Alamofire Manager extension. This solution uses EVReflection to serialize the 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 as follows:

 Alamofire.Manager.request(.POST, endpointUrlString, bodyObject: myObjectToPost) 
+8
Apr 05 '16 at 13:14
source share

If you want to publish the string as a raw body in the 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) })) 
+5
Mar 04 '16 at 6:20
source share

I did this for an array of strings. This solution is tailored for the string in the body.

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: [:]) 
+4
Feb 28 '17 at 16:03
source share
 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) 
+2
Jun 13 '16 at 13:12
source share

I used @afrodev's answer as a reference. In my case, I accept a parameter for my function as a string to be published in the 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) } } 
+2
Aug 18 '18 at 6:15
source share

Based on the response of Ilya Crete

the details

  • Xcode Version 10.2.1 (10E1001)
  • Swift 5
  • Alamofire 4.8.2

Decision

 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" } } } 

using

 Alamofire.request(url, method: .post, parameters: nil, encoding: BodyStringEncoding(body: text), headers: headers).responseJSON { response in print(response) } 
0
Jan 16 '19 at 20:16
source share

Xcode 8.X, Swift 3.X

Simple 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) } 
-3
Dec 15 '16 at 13:40
source share



All Articles