带有 JSON 字典的 POST 请求在 Swift 3 中使用 $_POST 没有返回正确的值? [英] POST Request with JSON dictionary does not return correct value with $_POST in Swift 3?
问题描述
我正在尝试提交要插入数据库的设备 IMEI.
I'm trying to do is submit the device IMEI to be inserted into the database.
但是,从数据库返回的 JSON 输出显示 IMEI 为 null
.
However, the returned JSON output from the database shows the IMEI as null
.
以下是已实施的内容:
请求者
class Requester
{
....
func postRequest(_ url: URL, headers : Dictionary<String,String>?, data: Data?, callback : @escaping (_ response: HTTPResponseWithData) -> Void) -> Void
{
let request = Factory.httpRequest(url, method: "POST", headers: headers, data: data)
let task = URLSession.shared.dataTask(with: request as URLRequest, completionHandler: {
data, response, error in
print("RESPONSE: \(response)");
})
task.resume()
}
....
}
工厂
class Factory
{
func httpRequest(_ url: URL, method: String, headers: Dictionary<String, String>?, data: Data?) -> URLRequest
{
var request = URLRequest(url: url)
request.httpMethod = method
if headers != nil
{
for (field, value) in headers!
{
request.addValue(value, forHTTPHeaderField: field)
}
}
if data != nil
{
request.httpBody = data
}
return request
}
}
MainVC
let requester = Requester()
@IBAction func sendRequest(_ sender: Any)
{
var json: Dictionary<String, Any> = [:]
json["imei"] = myIMEI
do
{
let data = try JSONSerialization.data(withJSONObject: json, options: .prettyPrinted)
post(theData: data)
}
catch let error as NSError
{
print(error.localizedDescription)
}
}
func post(theData: Data) -> Void
{
self.requester.postRequest("www.url.com", headers: nil, data: theData, callback: {(response: HTTPResponseWithData) -> Void in
if response.statusCode == 200 && response.data != nil && HTTPHeader.isContentTypeJSON(response.mimeType)
{
print(response.data!)
do
{
if let test = try JSONSerialization.jsonObject(with: response.data!, options: JSONSerialization.ReadingOptions()) as? Dictionary<String, Any>
{
print("test = \(test)")
}
}
catch
{
print("ERROR parsing data")
}
}
else
{
}
});
}
我从输出中得到的是:
test = ["imei": <null>]
我已经查看了许多关于 SO 的问题和答案,除了我在不同的类中的实现之外,我看不出可能有什么问题.
I've looked at numerous questions and answers on SO regarding this, and besides my implementation being in different classes, I don't see what could possibly be wrong.
这是 PHP 代码的一些片段:
Here's some snippet of the PHP code:
header("Content-Type: application/json");
$imei = $_POST["imei"];
$something_else = $_POST["something_else"];
$mysqli = new mysqli($host, $userid, $password, $database);
if ($mysqli->connect_errno)
{
echo json_encode(array("success" => false, "message" => $mysqli->connect_error, "sqlerrno" => $mysqli->connect_errno));
exit();
}
echo json_encode( array('imei'=>$imei) );
我的 POST 请求实现到底有什么问题,不允许我将 IMEI 提交到数据库?
What exactly is wrong with my POST request implementation that is not allowing me to submit the IMEI to the database?
如果有帮助,RESPONSE
输出是:
If it helps, the RESPONSE
output is:
响应:可选({ URL:http://www.url.com } { 状态码:200,标题{连接 = "保持活动";内容类型"=应用程序/json";日期 = "2017 年 1 月 2 日星期一 08:07:54 GMT";"Keep-Alive" = "timeout=2, max=96";服务器 = 阿帕奇;传输编码"= 身份;} })
RESPONSE: Optional( { URL: http://www.url.com } { status code: 200, headers { Connection = "Keep-Alive"; "Content-Type" = "application/json"; Date = "Mon, 02 Jan 2017 08:07:54 GMT"; "Keep-Alive" = "timeout=2, max=96"; Server = Apache; "Transfer-Encoding" = Identity; } })
UPDATE: 进一步测试后,我把上面的header
后面的php代码换成了下面的代码,现在报了imei
:
UPDATE: After further testing, I replaced the above php code after the header
with the following code, and now the imei
is reported:
$handle = fopen("php://input", "rb");
$raw_post_data = '';
while (!feof($handle))
{
$raw_post_data .= fread($handle, 8192);
}
fclose($handle);
$request_data = json_decode($raw_post_data, true);
$imei = $request_data["imei"];
我很困惑,为什么更新后的 php 代码有效,而涉及 $_POST
的却没有?
I'm confused, why is it the case that the updated php code works but the one involving $_POST
does not?
推荐答案
参见 $_POST
文档 说的是:
See the $_POST
documentation which says it is:
使用 application/x-www-form-urlencoded
或 multipart/form 时通过 HTTP
作为请求中的 HTTP POST
方法传递给当前脚本的关联变量数组-dataContent-Type
.
An associative array of variables passed to the current script via the HTTP
POST
method when usingapplication/x-www-form-urlencoded
ormultipart/form-data
as the HTTPContent-Type
in the request.
但你不是在执行 x-www-form-urlencoded
请求.您正在执行 application/json
请求.所以你不能使用 $_POST
.使用 php://input
(例如,正如这里所讨论的:iOS 发送 JSON 数据在使用 NSJSONSerialization 的 POST 请求中).
But you're not doing x-www-form-urlencoded
request. You're performing an application/json
request. So you can't use $_POST
. Use php://input
(e.g., as discussed here: iOS Send JSON data in POST request using NSJSONSerialization).
这篇关于带有 JSON 字典的 POST 请求在 Swift 3 中使用 $_POST 没有返回正确的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!