【问题标题】:Difference between Alamofire request and custom NSURLRequestAlamofire 请求和自定义 NSURLRequest 的区别
【发布时间】:2016-05-03 12:49:08
【问题描述】:

我使用 Alamofire 和自定义方法将NSURLMutableRequest 发布到 WebAPI,例如:

阿拉莫火

 Alamofire.request(.POST, "http://www.webapi.com?path=Login", parameters: ["username": "myname", "password": "mypass"]).responseJSON { response in
// do something with returned data ...
}

自定义

let request = NSMutableURLRequest(URL: NSURL(string:"http://www.webapi.com?path=Login")!)

let bodyData = "username=myname&password=mypass"
request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding)
request.HTTPMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")

let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())

    session.dataTaskWithRequest(request) { (data, response, error) -> Void in

    // do something with returned data...

    }.resume()

我通过 Alamofire 方法得到了正确的结果,但不是我自己的方法。

与 Alamofire 发布方法相比,我做错了什么?

【问题讨论】:

  • 你可以打开 Alamofire.request 方法。 alamofire 代码是开源的。
  • 当你说你得到了正确的结果; NSURLRequest 的错误结果是什么?是崩溃、任务返回的错误、错误的数据吗?
  • @keithbhunter 正确的结果是 json 格式的数据,错误的结果只是 nil

标签: ios swift http post alamofire


【解决方案1】:

您正在以["username": "myname", "password": "mypass"] 这种格式在alamofire 中传递参数,并以这种格式在自定义请求"username=myname&password=mypass" 中传递参数。所以两者都有区别。

第一个是json格式,第二个是字符串格式。

所以从您的自定义请求中发送 json 格式的数据。获取参数的dictionary 并使用NSJSONSerialization.dataWithJSONObject 将其转换为数据

希望这会有所帮助:)

【讨论】:

  • 我确实尝试了let jsonData = try NSJSONSerialization.dataWithJSONObject(["username": "myname", "password": "mypass"], options: .PrettyPrinted); request.setValue("application/json", forHTTPHeaderField: "Content-Type"); request.HTTPBody = jsonData;,但结果仍然为零。
  • option 应该是 0 而不是 prettyprinted
猜你喜欢
  • 2015-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多