Swift3:HTTP POST请求,参数除以" /"

时间:2016-11-22 03:07:37

标签: php ios swift swift3 httprequest

这是服务器(使用codeigniter)接受的可接受的POST请求。

如图所示,它不会获取键,而只是键值。

第一个值以" /"和" /"开头。在值之间使用。

#cover

我有这个用Swift3编写的代码。

http://example.com/index.php/api/signup/value01/value02/value03

收到错误,服务器回复说它没有收到任何参数。

但是,如果我将以下代码复制粘贴到浏览器,它就会完美无缺。

let serverUrl = "http://example.com/index.php/api/signup"
let parameterString = "/value01/value02/value03"

let url: URL = URL(string: serverUrl)!
let session = URLSession.shared
let request = NSMutableURLRequest(url: url)
request.httpMethod = "POST"
request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData
request.httpBody = parameterString.data(using: String.Encoding.utf8)

let task = session.dataTask(with: request as URLRequest, completionHandler: {(data, response, error) in 

}) task.resume()

swift3代码适用于另一台服务器,它接受以这种方式编写的POST请求。

http://example.com/index.php/api/signup/value01/value02/value03

1 个答案:

答案 0 :(得分:1)

谢谢@ Tj3n @Leo Dabus @ GoodSp33d!

我能够使用您的建议解决问题。

对于某些字符串值,服务器php还使用“URL-encode RFC 1738(例如”%E6%84%9B“为”爱“)”。

所以,我添加了

let newString = oldString.addingPercentEncoding(withAllowedCharacters:NSCharacterSet.urlQueryAllowed)!

编码一些字符串值并解决问题。

所以,这是简化版的解决方案。

let serverUrl = "http://example.com/index.php/api/signup/value01/value02/value03"

let url: URL = URL(string: serverUrl)!
let session = URLSession.shared
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData

let task = session.dataTask(with: request as URLRequest, completionHandler: {(data, response, error) in 

}) task.resume()

这是我的代码发送的真实POST请求网址。

http://example.com/index.php/api/signup/1282283772/none/0204291/%E6%84%9B/0/70/null