ios - 发布参数未从应用程序到达 API
<p><p>我有一个用于登录的 PHP API,它接受参数 - <code>login_id</code>、<code>password</code>、<code>imei_no</code>,并返回验证结果作为响应。我在向 iOS (Swift) 中的 API 发送请求时遇到问题。 API 接收空白参数。我已经使用相同的参数在 Postman 上运行了 API,它运行良好。 </p>
<p>请帮我找出代码中的错误。</p>
<pre><code>let parameters = ["login Id": "guest", "password": "guest123", "imei_no": 123456] as
print(parameters)
let request = NSMutableURLRequest(url: NSURL(string: "http://xxxxxxxxxxxxxxxxxxxxxxx/Appwebservice/loginAuth")! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "POST"
request.addValue("multipart/form-data", forHTTPHeaderField: "Content-Type")
let dataExample: Data = NSKeyedArchiver.archivedData(withRootObject: parameters)
request.httpBody = dataExample as Data
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
print(error)
} else {
let httpResponse = response as? HTTPURLResponse
print(httpResponse)
}
})
dataTask.resume()
}
</code></pre>
<p>我也试过 postman 给出的请求代码。 API 中的参数仍然显示为空白</p></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>因为你没有sneding 文件,你不应该使用<code>multipart/form-data</code>。它比 <code>application/x-www-form-urlencoded</code> 复杂得多。</p>
<p>您必须对参数进行编码,而不是归档它们。你可以这样做:</p>
<pre><code>let parameterArray = parameters.map { (key, value) -> String in
return "\(key)=\(value.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed))"
}
let parametersString = parameterArray.joinWithSeparator("&")
let dataExample = parametersString.data(using: .utf8)
</code></pre>
<p>使用此 <code>dataExample</code> 代替您的代码。</p></p>
<p style="font-size: 20px;">关于ios - 发布参数未从应用程序到达 API,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/47385959/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/47385959/
</a>
</p>
页:
[1]