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

php - JSON请求发送空数据(swift)


                                            <p><p>我的 iOS 应用正在向网络服务发送空数据。我花了几个小时寻找解决方案,但没有任何效果。
应用程序应该通过 php 脚本向数据库发送一个 kontrah 号码。然后数据库必须识别是否可以在数据库中找到康特拉数。然后,如果数字正确,我将收到来自数据库服务器的请求。问题是我发送的号码肯定是正确的。我检查了发送到数据库的内容,但都是空的:</p>

<pre><code>{&#34;kontrah&#34;:null,&#34;telefon&#34;:null,&#34;opis&#34;:null,&#34;afakt&#34;:null}
</code></pre>

<p>我在 Android Studio 中使用 Java 制作了相同的应用程序,但一切正常。</p>

<p>我的代码:</p>

<pre><code>@IBAction func submitAction(_ sender: AnyObject) {
    let kontrah: String = fkontrah.text!
   let telefon: String = ftelefon.text!



    let json = [ &#34;kontrah&#34; : (kontrah), &#34;telefon&#34; : (telefon), &#34;opis&#34; : (selectedvalue), &#34;afakt&#34; : (selectedafakt)]

    print (json)

    do {
      let jsonData = try JSONSerialization.data(withJSONObject: json, options: .prettyPrinted)
      print(jsonData)
      // create post request
      let url = NSURL(string: &#34;http://hetman.pl/ios/post2.php&#34;)!
      let request = NSMutableURLRequest(url: url as URL)
      request.httpMethod = &#34;POST&#34;

      // insert json data to the request
      request.setValue(&#34;application/json; charset=utf-8&#34;, forHTTPHeaderField: &#34;Content-Type&#34;)
      request.httpBody = jsonData



      let task = URLSession.shared.dataTask(with: request as URLRequest){ data, response, error in
            if error != nil{
                return
            }

            do {
                let t= try JSONSerialization.jsonObject(with: data!, options: []) as?
                print(t)

            } catch {
                print(&#34;Error43-&gt; \(error)&#34;)
            }
      }
      let alert = UIAlertController(title: &#34;Wysłano poprawnie&#34;, message: &#34;&#34;, preferredStyle: UIAlertControllerStyle.alert)
      alert.addAction(UIAlertAction(title: &#34;OK&#34;, style: UIAlertActionStyle.default, handler: nil))
      self.present(alert, animated: true, completion: nil)


      task.resume()


    }

    catch {
      //handle error. Probably return or mark function as throws
      print(error)
      return
    }
}
override func touchesBegan(_ touches: Set&lt;UITouch&gt;, with event: UIEvent?) {
    self.view.endEditing(true)
}

func textFieldShouldReturn(_ textField: UITextField) -&gt; Bool {
    textField.resignFirstResponder()
    return(true)
}

}
</code></pre>

<p>日志:</p>

<pre><code>2017-12-29 15:59:43.867463+0100 Hetman4 Failed to set (titleLabel.adjustsFontSizeToFitWidth) user defined inspected property on (UITextView): [&lt;UITextView 0x7fa1ad829e00&gt; valueForUndefinedKey:]: this class is not key value coding-compliant for the key titleLabel.
2017-12-29 15:59:47.717492+0100 Hetman4 System group container for systemgroup.com.apple.configurationprofiles path is /Users/bartoszlucinski/Library/Developer/CoreSimulator/Devices/3BE9103E-97CA-4E0B-AE53-6196EE08C49D/data/Containers/Shared/SystemGroup/systemgroup.com.apple.configurationprofiles
2017-12-29 15:59:47.717874+0100 Hetman4 Reading from private effective user settings.
2017-12-29 15:59:52.225804+0100 Hetman4 Can&#39;t find keyplane that supports type 4 for keyboard iPhone-PortraitChoco-NumberPad; using 4072550144015629828_PortraitChoco_iPhone-Simple-Pad_Default
[&#34;telefon&#34;: &#34;510356448&#34;, &#34;kontrah&#34;: &#34;1400-685&#34;, &#34;opis&#34;: &#34;Świnia&#34;, &#34;afakt&#34;: &#34;0&#34;]
94 bytes
2017-12-29 15:59:57.074868+0100 Hetman4 Failed to set (titleLabel.adjustsFontSizeToFitWidth) user defined inspected property on (UITextView): [&lt;UITextView 0x7fa1b0096400&gt; valueForUndefinedKey:]: this class is not key value coding-compliant for the key titleLabel.
2017-12-29 15:59:57.628832+0100 Hetman4 Presenting view controllers on detached view controllers is discouraged &lt;Hetman4.ViewController: 0x7fa1ac428ef0&gt;.
Optional([&#34;error&#34;: &lt;null&gt;, &#34;result&#34;: kontrahdoesn&#39;t exist, &#34;unAuthorizedRequest&#34;: 0, &#34;success&#34;: 1])
</code></pre>

<p>PHP 脚本:</p>

<pre><code>&lt;?php
$kontrah = urlencode($_POST[&#39;kontrah&#39;]);
$telefon = urlencode($_POST[&#39;telefon&#39;]);
$opis = urlencode($_POST[&#39;opis&#39;]);
$afakt = urlencode($_POST[&#39;afakt&#39;]);

$url = &#39;https://hetman.e4b.com.pl/api/services/app/zlecenie/FormAddZlecenie?kontrah=&#39;.$kontrah.&#39;&amp;telefon=&#39;.$telefon.&#39;&amp;opis=&#39;.$opis.&#39;&amp;afakt=&#39;.&amp;afakt;

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);


$results = curl_exec($ch);

curl_close($ch);
?&gt;
</code></pre></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>几个问题:</p>

<ol>
<li><p>您的服务器期待 <code>application/x-www-form-urlencoded</code> 请求,而不是 JSON 请求。响应是 JSON,但请求不是。</p></li>
<li><p>当我使用 <code>hetman.pl</code> URL,但它重定向到 <code>www.hetman.pl</code>,但将 <code>POST</code> 替换为<code>获取</code>。当我直接向 <code>www.hetman.pl</code> 发送请求时,我收到了不同的消息。不过,我看不懂它们,所以我无法评论这是好是坏。</p></li>
<li><p>与手头的问题无关,可以稍微整理一下 Swift 代码,将 <code>NSURL</code> 和 <code>NSURLRequest</code> 替换为 <code>URL</code>和 <code>URLRequest</code>。</p></li>
</ol>

<p>综合起来,你会得到如下结果:</p>

<pre><code>let parameters = [&#34;kontrah&#34; : kontrah, &#34;telefon&#34; : telefon, &#34;opis&#34; : selectedvalue, &#34;afakt&#34; : selectedafakt]

let url = URL(string: &#34;http://www.hetman.pl/ios/post2.php&#34;)!
var request = URLRequest(url: url)
request.httpMethod = &#34;POST&#34;
request.setValue(&#34;application/json&#34;, forHTTPHeaderField: &#34;Accept&#34;)
request.setValue(&#34;application/x-www-form-urlencoded; charset=utf-8&#34;, forHTTPHeaderField: &#34;Content-Type&#34;)
request.setBodyContent(parameters)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    guard let data = data, error == nil else {
      print(error ?? &#34;Unknown error&#34;)
      return
    }

    do {
      let t= try JSONSerialization.jsonObject(with: data) as?
      print(t ?? &#34;Invalid&#34;)
    } catch {
      print(&#34;Error43-&gt; \(error)&#34;)
    }
}
task.resume()
</code></pre>

<p>在哪里</p>

<pre><code>extension URLRequest {

    /// Populate the HTTPBody of `application/x-www-form-urlencoded` request
    ///
    /// - parameter parameters:   A dictionary of keys and values to be added to the request

    mutating func setBodyContent(_ parameters: ) {
      let parameterArray = parameters.map { (key, value) -&gt; String in
            let encodedKey   = key.addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed)!
            let encodedValue = value.addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed)!
            return &#34;\(encodedKey)=\(encodedValue)&#34;
      }
      httpBody = parameterArray
            .joined(separator: &#34;&amp;&#34;)
            .data(using: .utf8)
    }
}

extension CharacterSet {

    /// Character set containing characters allowed in query value as outlined in RFC 3986.
    ///
    /// RFC 3986 states that the following characters are &#34;reserved&#34; characters.
    ///
    /// - General Delimiters: &#34;:&#34;, &#34;#&#34;, &#34;[&#34;, &#34;]&#34;, &#34;@&#34;, &#34;?&#34;, &#34;/&#34;
    /// - Sub-Delimiters: &#34;!&#34;, &#34;$&#34;, &#34;&amp;&#34;, &#34;&#39;&#34;, &#34;(&#34;, &#34;)&#34;, &#34;*&#34;, &#34;+&#34;, &#34;,&#34;, &#34;;&#34;, &#34;=&#34;
    ///
    /// In RFC 3986 - Section 3.4, it states that the &#34;?&#34; and &#34;/&#34; characters should not be escaped to allow
    /// query strings to include a URL. Therefore, all &#34;reserved&#34; characters with the exception of &#34;?&#34; and &#34;/&#34;
    /// should be percent-escaped in the query string.
    ///
    /// - parameter string: The string to be percent-escaped.
    ///
    /// - returns: The percent-escaped string.

    static var urlQueryValueAllowed: CharacterSet = {
      let generalDelimitersToEncode = &#34;:#[]@&#34; // does not include &#34;?&#34; or &#34;/&#34; due to RFC 3986 - Section 3.4
      let subDelimitersToEncode = &#34;!$&amp;&#39;()*+,;=&#34;

      var allowed = CharacterSet.urlQueryAllowed
      allowed.remove(charactersIn: generalDelimitersToEncode + subDelimitersToEncode)

      return allowed
    }()

}
</code></pre></p>
                                   
                                                <p style="font-size: 20px;">关于php - JSON请求发送空数据(swift),我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/48025086/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/48025086/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: php - JSON请求发送空数据(swift)