简体   繁体   English

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

[英]Swift3: HTTP POST request with parameters divided by “/”

This is the acceptable POST request that server(using codeigniter) accepts. 这是服务器(使用codeigniter)接受的可接受的POST请求。

As it is shown, it doesn't take keys, but only values. 如图所示,它不需要键,而只需要值。

The first value starts with "/", and "/" is used between values. 第一个值以“ /”开头,在两个值之间使用“ /”。

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

I have this code, written in Swift3. 我有用Swift3编写的代码。

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()

It gets an error, and the server responds that it didn't receive any parameter. 它得到一个错误,并且服务器响应它没有收到任何参数。

But, if I copy paste the below code to Browser, it works perfect. 但是,如果我将以下代码复制粘贴到浏览器中,则效果很好。

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

The swift3 code worked for another server, which accepted POST requests written this way. swift3代码可用于另一台服务器,该服务器接受以这种方式编写的POST请求。

http://example.com/api?key=value&key=value

Thank you @Tj3n @Leo Dabus @GoodSp33d ! 谢谢@ Tj3n @Leo Dabus @ GoodSp33d!

I was able to solve the problem, using your suggestions. 我能够根据您的建议解决问题。

The server php also used "URL-encode RFC 1738 (eg "%E6%84%9B" for "愛")" for certain string values. 服务器php还对某些字符串值使用“ URL编码RFC 1738(例如,“爱”的“%E6%84%9B”))。

So, I added 所以,我加了

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

to encode some string values and the problem solved. 编码一些字符串值并解决了问题。

So, this is the solution in a simplified version. 因此,这是简化版本中的解决方案。

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()

This is the real POST request url that my code sent. 这是我的代码发送的真实POST请求网址。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM