POST request with a simple string in body with Ala

2019-01-04 08:26发布

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.com/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.com/post-request", body: "myBodyString")

9条回答
Explosion°爆炸
2楼-- · 2019-01-04 09:13

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)
        }))
查看更多
倾城 Initia
3楼-- · 2019-01-04 09:14

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: [:])
查看更多
beautiful°
4楼-- · 2019-01-04 09:18

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)
查看更多
登录 后发表回答