POST Request with JSON dictionary does not return

2019-08-03 10:06发布

I'm trying to do is submit the device IMEI to be inserted into the database.

However, the returned JSON output from the database shows the IMEI as null.

Here's what's been implemented:

Requester

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()
    }

    ....
}

Factory

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
        {

        }
    });
}

What I get back from the output is:

test = ["imei": <null>]

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.

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) );

What exactly is wrong with my POST request implementation that is not allowing me to submit the IMEI to the database?

If it helps, the RESPONSE output is:

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: 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"];

I'm confused, why is it the case that the updated php code works but the one involving $_POST does not?

标签: php swift swift3
1条回答
Explosion°爆炸
2楼-- · 2019-08-03 10:22

See the $_POST documentation which says it is:

An associative array of variables passed to the current script via the HTTP POST method when using application/x-www-form-urlencoded or multipart/form-data as the HTTP Content-Type in the request.

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).

查看更多
登录 后发表回答