如何在SWIFT中发送http post请求?

时间:2016-07-13 12:04:19

标签: ios swift

请更正此代码

@IBAction func registeruser(sender: AnyObject) {
    let usertext = useremail.text;

    let myURL = NSURL(string: "http://advaluead.com/vishwa/index.php");
    let request = NSMutableURLRequest(URL:myURL!);
    request.HTTPMethod = "POST";

    let poststring = "email=\(usertext)";
    request.HTTPBody = poststring.dataUsingEncoding(NSUTF8StringEncoding);

}

我的服务器没有收到应用程序的任何请求。

2 个答案:

答案 0 :(得分:1)

let myURL = NSURL(string: "http://advaluead.com/vishwa/index.php");
            let postData:NSData = post.dataUsingEncoding(NSASCIIStringEncoding)!
            let postLength:NSString = String( postData.length )
            let request:NSMutableURLRequest = NSMutableURLRequest(URL: url!)
            request.timeoutInterval = 120
            request.HTTPMethod = "POST"
            request.HTTPBody = postData
            request.setValue(postLength as String, forHTTPHeaderField: "Content-Length")
            request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
            request.setValue("application/json", forHTTPHeaderField: "Accept")

请。检查一次。

答案 1 :(得分:0)

您需要禁用ATS(App Transport Security)或授权域名,因为您没有使用https。

要“残酷地”禁用所有http调用(不是最佳选项),请将其添加到您的Info.plist中:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

建议的方法是保持ATS并以这种方式配置域异常:

<key>NSAppTransportSecurity</key>
<dict>
  <key>NSExceptionDomains</key>
  <dict>
    <key>yourserver.com</key>
    <dict>
      <!--Include to allow subdomains-->
      <key>NSIncludesSubdomains</key>
      <true/>
      <!--Include to allow HTTP requests-->
      <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
      <true/>
      <!--Include to specify minimum TLS version-->
      <key>NSTemporaryExceptionMinimumTLSVersion</key>
      <string>TLSv1.1</string>
    </dict>
  </dict>
</dict>

More info here