美文网首页
URLRequest设置`Content-Type`请求头

URLRequest设置`Content-Type`请求头

作者: flionel | 来源:发表于2017-10-17 19:53 被阅读433次
49ers.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请求。

相关文章

网友评论

      本文标题:URLRequest设置`Content-Type`请求头

      本文链接:https://www.haomeiwen.com/subject/wiqjuxtx.html