如何在 alamofire 中 post 简单字符串(不是字典)?
How to post simple string (not dictionary) in alamofire?
我必须 post 正文中的原始字符串。
通常情况下,我是这样做的。
let parameters = ["asdf": "asdf", "fdsa", "fdsa"]
AF.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default).responseJSON.......
但是如何 post 原始字符串? (这不是 json 字符串。只是字符串。)
AF.request(url, method: .post, parameters: "jsut simple string", encoding: JSONEncoding.default).responseJSON.......
我该怎么做?
您可以使用以下自定义编码在参数中发送单个值,并在参数
中传递[:]
空字典
struct SingleValueEncoding: ParameterEncoding {
private let value: String
init(value: String) {
self.value = value
}
func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
var urlRequest = urlRequest.urlRequest
let data = value.data(using: .utf8)!
if urlRequest?.value(forHTTPHeaderField: "Content-Type") == nil {
urlRequest?.setValue("application/json", forHTTPHeaderField: "Content-Type")
}
urlRequest?.httpBody = data
return urlRequest!
}
}
在 Alamofire 请求中,Parameters
是 dictionary
/// A dictionary of parameters to apply to a `URLRequest`.
public typealias Parameters = [String: Any]
Alamofire 5 现在支持 Encodable
类型作为参数。如果您只想编码 String
,请切换到使用 Request
:
的形式
AF.request(url, method: .post, parameters: "just simple string", encoder: JSONParameterEncoder.default)
注意 encoder
而不是 encoding
参数名称和新的 JSONParameterEncoder
类型。
此外,不再推荐使用 responeJSON
,使用 responseDecodable
生成 Decodable
类型将是更好的方法。
我必须 post 正文中的原始字符串。
通常情况下,我是这样做的。
let parameters = ["asdf": "asdf", "fdsa", "fdsa"]
AF.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default).responseJSON.......
但是如何 post 原始字符串? (这不是 json 字符串。只是字符串。)
AF.request(url, method: .post, parameters: "jsut simple string", encoding: JSONEncoding.default).responseJSON.......
我该怎么做?
您可以使用以下自定义编码在参数中发送单个值,并在参数
中传递[:]
空字典
struct SingleValueEncoding: ParameterEncoding {
private let value: String
init(value: String) {
self.value = value
}
func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
var urlRequest = urlRequest.urlRequest
let data = value.data(using: .utf8)!
if urlRequest?.value(forHTTPHeaderField: "Content-Type") == nil {
urlRequest?.setValue("application/json", forHTTPHeaderField: "Content-Type")
}
urlRequest?.httpBody = data
return urlRequest!
}
}
在 Alamofire 请求中,Parameters
是 dictionary
/// A dictionary of parameters to apply to a `URLRequest`.
public typealias Parameters = [String: Any]
Alamofire 5 现在支持 Encodable
类型作为参数。如果您只想编码 String
,请切换到使用 Request
:
AF.request(url, method: .post, parameters: "just simple string", encoder: JSONParameterEncoder.default)
注意 encoder
而不是 encoding
参数名称和新的 JSONParameterEncoder
类型。
此外,不再推荐使用 responeJSON
,使用 responseDecodable
生成 Decodable
类型将是更好的方法。