ios - 如何正确创建 httpBody?

标签 ios swift http content-type

我想创建 POST 方法的主体

Content-Type: application/x-www-form-urlencoded

我有一本字典

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

我尝试使用 URLComponents 转换和转义字典。但是在HTTP规范中没有发现那些转义方式是一样的。

有人知道执行此操作的正确解决方案吗?

我看过

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

https://www.rfc-editor.org/rfc/rfc1866

https://www.rfc-editor.org/rfc/rfc1738

https://www.rfc-editor.org/rfc/rfc3986

最佳答案

你可以而且应该使用 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 .

关于ios - 如何正确创建 httpBody?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47921940/

相关文章:

ios - PHAdjustmentData 大小限制

swift - 在 Swift 3 中使用 NSHashTable 实现观察者模式

ios - Cocoapods 项目中出现很多错误

Android改造导致socket超时异常

c# - 获取请求的 Authorization header 值的最简单方法是什么?

ios - RegisterUserNotificationSettings 在 ios 6.1 中不起作用

iphone - 从 NSMutableArray 中拉出 NSArray

ios - [NSDateFormatter 类] : message sent to deallocated instance

ios - 如何让一个 View Controller 从另一个 View Controller 访问变量?

PHP 不能在带有 http_build_query() 的数组中使用 'not'