POST请求与一个简单的string与Alamofire正文
在我的iOS应用程序中,如何使用Alamofire在HTTP正文中使用简单string发送POST请求?
默认情况下,Alamofire需要一个请求的参数:
Alamofire.request(.POST, "http://mywebsite.com/post-request", parameters: ["foo": "bar"])
这些参数包含键值对。 但我不想在HTTP正文中使用键值string发送请求。
我的意思是这样的:
Alamofire.request(.POST, "http://mywebsite.com/post-request", body: "myBodyString")
您的示例Alamofire.request(.POST, "http://mywebsite.com/post-request", parameters: ["foo": "bar"])
已经包含“foo = bar”string作为其正文。 但是,如果你真的想要自定义格式的string。 你可以这样做:
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: [:])
你可以这样做:
- 我创build了一个分离的请求Alamofire对象。
- 将string转换为数据
-
把httpBody的数据
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) }
我修改了@Silmaril的答案来扩展Alamofire的经理。 此解决scheme使用EVReflection直接序列化对象:
//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) }) ) } }
那么你可以像这样使用它:
Alamofire.Manager.request(.POST, endpointUrlString, bodyObject: myObjectToPost)
如果您使用Alamofire,那么编码types到“URLEncoding.httpBody”
有了这个,你可以在httpbody中把你的数据作为一个string发送,尽pipe你在代码中定义了json。
它为我工作..
更新
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"]!) } })
如果你想在请求中发布string作为原始的身体
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) }))
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)
我已经做了从string数组。 这个解决scheme是针对string进行调整的。
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! }}
然后用你的要求:
Alamofire.request("your url string", method: .post, parameters: [:], encoding: JSONStringArrayEncoding.init(string: "My string for body"), headers: [:])
Xcode 8.X,Swift 3.X
易于使用;
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) }