使用 Alamofire 在正文中使用简单字符串的 POST 请求 [英] POST request with a simple string in body with Alamofire

查看:70
本文介绍了使用 Alamofire 在正文中使用简单字符串的 POST 请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在我的 iOS 应用程序中使用 Alamofire 在 HTTP 正文中发送带有简单字符串的 POST 请求?

how is it possible to send a POST request with a simple string in the HTTP body with Alamofire in my iOS app?

默认情况下,Alamofire 需要请求参数:

As default Alamofire needs parameters for a request:

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

这些参数包含键值对.但我不想在 HTTP 正文中发送带有键值字符串的请求.

These parameters contain key-value-pairs. But I don't want to send a request with a key-value string in the HTTP body.

我的意思是这样的:

Alamofire.request(.POST, "http://mywebsite.com/post-request", body: "myBodyString")

推荐答案

你的例子 Alamofire.request(.POST, "http://mywebsite.com/post-request", parameters: ["foo":"bar"]) 已经包含 "foo=bar" 字符串作为它的主体.但是如果你真的想要自定义格式的字符串.你可以这样做:

Your example Alamofire.request(.POST, "http://mywebsite.com/post-request", parameters: ["foo": "bar"]) already contains "foo=bar" string as its body. But if you really want string with custom format. You can do this:

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

注意:参数不能为nil

更新(Alamofire 4.0、Swift 3.0):

在 Alamofire 4.0 中 API 已更改.因此对于自定义编码,我们需要符合 ParameterEncoding 协议的值/对象.

In Alamofire 4.0 API has changed. So for custom encoding we need value/object which conforms to 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: [:])

这篇关于使用 Alamofire 在正文中使用简单字符串的 POST 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆