ios - 无法将数据发布到php页面

时间:2017-01-23 16:30:34

标签: php ios

我想将一些数据发布到我的php页面,我已经测试了两种方法,但不是这些方法有效:

let parameters = [
        "name": "test",
    ]

    Alamofire.request(URL(string: "http://www.tameshkshop.ir/11.php")!, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: [:]).responseJSON { (response) in
        print(response.request)  // original URL request
        print(response.response) // URL response
        print(response.data)     // server data
        print(response.result)   // result of response serialization


        let responseString = String(data: response.data!, encoding: .utf8)

        print(responseString)

    }
第二种方式:

var request = URLRequest(url: URL(string: "http://www.tameshkshop.ir/11.php")!)
    request.httpMethod = "POST"
    let postString = "name=\(FinallFactorViewController.name)"        
    request.httpBody = postString.data(using: .)
    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data, error == nil else {                                                 // check for fundamental networking error
            print("error=\(error)")
            return
        }

        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // check for http errors
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(response)")
        }

        let responseString = String(data: data, encoding: .utf8)

        let index = responseString?.index((responseString?.startIndex)!, offsetBy: 4)
       let done = responseString?.substring(to: index!)

在php页面中,我得到了发布的值,并像这样回复它们:

echo     $_POST['name'];

但我得不到任何回报。

有什么不对?我在哪里做错了?

1 个答案:

答案 0 :(得分:0)

您的POST服务正在等待httpBody参数,而不是JSON。我确实在邮递员身上检查了这个。使用以下代码提出您的请求:

let parameters = ["name":"Name"]
        Alamofire.request(.POST, "http://tameshkshop.ir/11.php", parameters: parameters)
            .responseString(completionHandler: { response in
                print(response.result.value)
            })

输出:

"test : Name |"

修改 自iOS 9起,您无法使用HTTP发出请求。请在.plist https://stackoverflow.com/a/33712228/5006492中使用HTTPS或允许任意加载。在开始生产之前禁用允许任意加载< / strong>,是使用HTTP的安全风险。获取您网站的SSL证书。