ios - Swift 中使用 NSJSONSerialization.dataWithJSONObject 和 dataUsingEncoding 组成 HTTP body 的区别

标签 ios objective-c swift http

我见过两种组成HTTP body的方法。
第一个是:

let url = NSURL(string: "http://example.com")  
let request = NSMutableURLRequest(URL: url!)  
request.HTTPMethod = "POST"  
let postString = "id=13&name=Jack"  
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)  

第二个是:

let url = NSURL(string: "http://example.com")  
let request = NSMutableURLRequest(URL: url!)  
request.HTTPMethod = "POST"  
let params = ["id":"13", "name":"Jack"] as Dictionary<String, String>
var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err)

当我直接打印出request.HTTPBody的数据是不一样的。所以我想知道这两种方法在服务器端的实现方面有什么区别吗?假设我正在使用 PHP。

最佳答案

有两种格式的数据。

在使用 postString.dataUsingEncoding 的代码中,它将以 urlencoded 格式发送数据。在客户端中,您必须将请求的 Content-Type header 设置为 "application/x-www-form-urlencoded" 或类似 "application/x-www-form-urlencoded charset=utf-8 “

在使用 NSJSONSerialization.dataWithJSONObject 的代码中,它将以 json 格式发送数据。在客户端中,您必须将请求的 Content-Type header 字段设置为 "application/json"

我是 iOS 开发人员,所以我不知道格式对服务器端 PHP 的影响。要回答您的问题,您必须找到服务器端 application/x-www-form-urlencodedapplication/json 格式之间的区别

关于ios - Swift 中使用 NSJSONSerialization.dataWithJSONObject 和 dataUsingEncoding 组成 HTTP body 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31174560/

相关文章:

ios - 如何知道 View 中心是否与其他 View 中心重合?

ios - 如何设置 UICollectionView 填充 UIEdgeInsets

ios - 如何将未知人员 ViewController 与最初输入的生成数据一起使用?

iphone - 我可以使用 Javascript(或任何网络技术)将变量从 UIWebView 传回我的应用程序吗?

swift - 在ios swift4中通过纬度和经度创建 map 图像

ios - 'textStorage' 是一个只读属性 - 为 UITextView 使用 MarkdownKit 框架时出错

ios - 如何添加约束以右对齐 UITableViewCell 内的图像

ios - 改变CALayer位置的目的是什么

ios - iOS 8 中呈现的 View Controller 中的界面方向不正确

swift - : Separator. Iterator.Element == Self.Iterator.Element.Iterator.Element 是什么意思