POST request on Swift does not work

Asked

Viewed 288 times

1

Good morning, I searched for several sites a way to make a POST request to a server, found several forms and tested them all, but none worked. I can receive page data and even send GET variables to the URL, but POST variables are simply not sent.

func teste(){

    var request = NSMutableURLRequest(URL: NSURL(string: "http://minhaurl/efetuarLogin.php?variavel=teste&get=valor")!)

    var session = NSURLSession.sharedSession()

    request.HTTPMethod = "POST"

    var params = ["CPF":"00000000000", "senha":"12345678"] as Dictionary

    var err: NSError?

    request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err)
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")

    var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in

        var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
        var err: NSError?

        var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &err) as NSDictionary

        if((err) != nil) {

            println(err!.localizedDescription)

        } else {

            println("JSON: \(json)")

        }

    })

    task.resume()

}

On the PHP page I try to access the variables through $_POST, $_GET and even $_REQUEST, only the GET variables are received on the server.

Can anyone tell me what could be going wrong? From now on, thank you.

2 answers

1

How what is being sent is a JSON, with header and everything, don’t expect to receive your server-side variables (CPF and password) as $_POST['senha'] for example, since it was not a form that was sent.

You need to get the "body" of the request, which is a JSON, decode and then yes you will have the variables you need. On the server side, with PHP try something like this:

$inputJSON = file_get_contents('php://input');
$input = json_decode($inputJSON, TRUE);

// $input['CPF'], $input['senha']

In the iOS is all right. See if this solves your question.

  • Should file_get_contents receive "php://input" itself or should I put something else? That way the return was "<null>" :(

  • Yes. Before you could check the variable value $inputJSON?

  • Returning inputJSON gets an empty string ""

  • Do you have access to the server to check if there was an error? A point to remember, is that the function file_get_contents needs the directive allow_url_fopen of active PHP.

  • I thought at first that it was some kind of server lock, but the administrator made sure that there was no lock on that address. The directives are as follows: allow_url_fopen: On; allow_url_include: Off; always_populate_raw_post_data: Off;

  • Well, then in that case you need to see if JSON is really going on the request. I noticed that in your code you did not verify if there was error when you used the method dataWithJSONObject. See if the variable err has an error. I usually use in the options of this method the .PrettyPrinted. This can cause a malformed json.

  • err and error (from the dataWithJSONObject method) are null (nil). Is it safe to pass them via GET? Is the way I’m doing it safe? Via GET is much easier, if it’s safe it pays a lot more to do via GET, I’ve been stuck in it for a long time.

Show 3 more comments

0

In the implementation you posted there are no errors, it’s just a very simple request.

Try removing the parameters from your URL in the request as it may be being processed by the server and ignoring your httpBody.

  • The actual code does not have these parameters, I put them here in the question to indicate that the sending variables GET works.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.