gpt4 book ai didi

php - HTTPS POST 工作成功,但变量为空

转载 作者:行者123 更新时间:2023-11-30 12:16:56 25 4
gpt4 key购买 nike

我在这里发布的代码是一个简短的版本,仅包含该问题的要点。经过严格的错误测试后,除了服务器的响应显示“Function”:null 而不是“Function”之外,请求内、服务器内或返回代码内似乎都没有问题:“addUser”,因为它应该。我在两端都做错了什么吗?它似乎只是无法识别发布的变量,但我在其他应用程序和服务器中多次使用了此代码,并且由于某种我看不到的原因,它似乎在这里失败了。感谢您的帮助。

这是我在服务器上的 PHP:

<?php
$t = $_POST["function"];
$do = array("Success"=>true, "Function"=> $t);
echo json_encode($do);
?>

这是我用来发出请求的 swift:

  let params = ["function": "addUser"] as [String: AnyObject]?


fetchData("https://pdt.pitchprogress.net/SamplePHP.php", token: nil, parameters: params, method: "POST", onCompletion: { (success, data) -> Void in
if success {
do {
let json = try JSON(data: data!)
if json["Success"].boolValue == true {
print("success!")
print(json.description)
print(json["Function"].stringValue)
}
}
}
})




func fetchData(_ feed:String,token:String? = nil,parameters:[String:AnyObject]? = nil,method:String? = nil, onCompletion:@escaping (_ success:Bool,_ data:Data?)->Void){

DispatchQueue.main.async {


if let unwrapped_url = URL(string: feed){
let request = NSMutableURLRequest(url: unwrapped_url)

if let parm = parameters {
if let data = (try? JSONSerialization.data(withJSONObject: parm, options:[])) as Data? {

request.httpBody = data
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("\(data.count)", forHTTPHeaderField: "Content-Length")

}
}

if let unwrapped_method = method {
request.httpMethod = unwrapped_method
}

let sessionConfiguration = URLSessionConfiguration.default
sessionConfiguration.timeoutIntervalForRequest = 15.0
let session = URLSession(configuration: sessionConfiguration)

let taskGetCategories = session.dataTask(with: request as URLRequest, completionHandler: { (responseData, response, error) -> Void in

let statusCode = (response as! HTTPURLResponse?)?.statusCode
//println("Status Code: \(statusCode), error: \(error)")
if error != nil || (statusCode != 200 && statusCode != 201 && statusCode != 202){
onCompletion(false, nil)

} else {
onCompletion(true, responseData)
}
})

taskGetCategories.resume()
}
}
}

最佳答案

这是因为您以 JSON 形式发送参数,而您的 API 需要将参数作为表单数据。

此代码将参数作为简单的表单帖子发送,并检索到成功的响应。

var request = URLRequest(url: URL(string: "http://app123.freeiz.com/Apis/samples/api4.php")!)
request.httpMethod = "POST"
var postString = ""
postString.append("function=value") // replace 'function' with your paramname and 'value' with your value'
request.httpBody = postString.data(using: .utf8)

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=\(String(describing: 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 = \(String(describing: response))")
}

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

if let unWrappedResponseString = responseString{

print(unWrappedResponseString)
}

}
task.resume()

我曾经制作过一个用于发送简单表单数据的小包装器,如果我找到它,我将用它更新答案。在那之前你可以尝试一下。让我知道进展如何..

关于php - HTTPS POST 工作成功,但变量为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45314682/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com