如何正确创建httpBody?

时间:2017-12-21 09:35:29

标签: ios swift http content-type

我想用

创建POST方法的主体
Content-Type: application/x-www-form-urlencoded

我有一本字典

let params = ["key":"val","key1":"val1"]

我尝试使用URLComponents转换和转义字典。但是在HTTP规范中没有找到那些转义方法是相同的。

有人知道这样做的正确解决方案吗?

我看了

https://tools.ietf.org/html/draft-hoehrmann-urlencoded-01

https://tools.ietf.org/html/rfc1866

https://tools.ietf.org/html/rfc1738

https://tools.ietf.org/html/rfc3986

1 个答案:

答案 0 :(得分:1)

您可以而且应该使用NSURLComponents创建正文:

let components = NSURLComponents()

components.queryItems = [ 
    URLQueryItem(name: "key", value: "val"), 
    URLQueryItem(name: "key1", value: "val1")
]
if let query = components.query {
    let request = NSMutableURLRequest()

    request.url = ...
    request.allHTTPHeaderFields = [ "Content-Type": "application/x-www-form-urlencoded"]
    request.httpBody = query.data(using: .utf8)
}

NSURLComponents从数据创建有效的URL,并将有效的URL解析为其组件。具有上述内容类型的HTTP发布请求的正文应包含参数作为URL查询(请参阅How are parameters sent in an HTTP POST request?)。

NSURLComponents是一个不错的选择,因为它可以确保符合标准。

另请参阅:WikipediaW3C