![](https://img.haomeiwen.com/i931525/6bd01b6b1fad98a4.jpg)
1. Alamofire中的范例代码
Alamofire的ParameterEncoding文件中,分别进行了URLEncoding, JSONEncoding以及PropertyListEncoding,其中分别设置了HTTP的Content-Type
请求头,如下所示,
1.1 x-www.form-urlencoded
// URLEncoding
urlRequest.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
let parameters = [String: Any]
urlRequest.httpBody = parameters.map { "\($0.0)=\($0.1)" }.joined(separator: "&")
1.2 application/json
// JOSNEncoding
urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
urlRequest.httpBody = JSONSerialization.data(...)
// PropertyListEncoding
1.3 application/x-plist
urlRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type")
urlRequest.httpBody = PropertyListSerialization.data(...)
2. Content-Type简介
Content-Type请求头用于指定请求和响应的HTTP内容类型,如果未指定Content-Type,默认为text/html。
在iOS开发中,有如下常用的Content-Type,
- application/x-www.form-urlencoded,是常用的表单发包方式,在Alamofire的get请求中,默认是这种方式;
- multipart/form-data 用在发送文件的POST请求中;
- application/json 通过json的数据形式发送HTTP请求;
- application/x-plist 通过propertyList的数据形式发送HTTP请求。
网友评论