菜鸟教程小白 发表于 2022-12-11 19:19:58

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 = [&#34;login Id&#34;: &#34;guest&#34;, &#34;password&#34;: &#34;guest123&#34;, &#34;imei_no&#34;: 123456] as
    print(parameters)


    let request = NSMutableURLRequest(url: NSURL(string: &#34;http://xxxxxxxxxxxxxxxxxxxxxxx/Appwebservice/loginAuth&#34;)! as URL,
                                    cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
    request.httpMethod = &#34;POST&#34;
    request.addValue(&#34;multipart/form-data&#34;, forHTTPHeaderField: &#34;Content-Type&#34;)
    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) -&gt; 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) -&gt; String in
    return &#34;\(key)=\(value.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed))&#34;
}
let parametersString = parameterArray.joinWithSeparator(&#34;&amp;&#34;)
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]
查看完整版本: ios - 发布参数未从应用程序到达 API