您的示例Alamofire.request(.POST, "http://mywebsite.com/post-request", parameters: ["foo": "bar"])
已经包含“ foo = bar”字符串作为其主体。但是,如果您真的要使用自定义格式的字符串。你可以这样做:
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)
}))
注意:parameters
不应该nil
更新(Alamofire 4.0,Swift 3.0):
在Alamofire 4.0中,API已更改。因此,对于自定义编码,我们需要符合ParameterEncoding
协议的值/对象。
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: [:])