如何正确创建httpBody?

问题描述 投票:1回答:1

我想创建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

ios swift http content-type
1个回答
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

© www.soinside.com 2019 - 2024. All rights reserved.