PostAsJsonAsync POST variables don't arrive at Flight PHP REST server

1.4k views Asked by At

I have a Flight PHP REST server set up. At 1 end point it expects POST data and based on one of the POST data it retrieves some data from the database and returns it as JSON.

When I use the Postman REST extension in Chrome I see the correct result. But when I do the call using my C# application the returned json is null because the $_POST seems empty.

This is my Flight index.php:

Flight::route('POST /getText', function(){  
  // Create a new report class:
  $reportText = new ReportText;
  $theText = $reportText->ParsePost($_POST);
  if ($theText == null)
  {
    echo null;
  }
  else
  {
    echo json_encode($theText);
  }        
});

This is my ParsePost:

public function ParsePost($PostDictionary)
{
    $textArray = null;
    foreach ($PostDictionary as $key => $value)
    {
        if (!empty($value))
        {
            list($tmp, $id) = explode("_", $key);
            $text = $this->geFooWithText($id);
            $textArray[$key] = "bar";
        }
    }

    return $textArray;
}

This is my C# part:

private static async Task RunAsyncPost(string requestUri)
{
    using (var client = new HttpClient())
    {
        // Send HTTP requests
        client.BaseAddress = new Uri("myUrl");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        try
        {
            // HTTP POST
            var response = await client.PostAsJsonAsync(requestUri, new { question_8 = "foo", question_9 = "bar" });
            response.EnsureSuccessStatusCode(); // Throw if not a success code.
            if (response.IsSuccessStatusCode)
            {
                var json = await response.Content.ReadAsStringAsync();
                if (string.IsNullOrEmpty(json))
                {
                    throw new ArgumentNullException("json", @"Response from the server is null");    
                }

                var dictionary = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);

                foreach (var kvp in dictionary)
                {
                    Debug.WriteLine("Key: {0}, Value: {1}", kvp.Key, kvp.Value);
                }
            }
        }
        catch (HttpRequestException e)
        {
            // Handle exception.
            Debug.WriteLine(e.ToString());
            throw;
        }
    }
}

This is the response from Postman:

{
  "question_8": "foo",
  "question_9": "bar"
}

It seems I'm missing something in my call using C#.

[Update]

In this post (Unable to do a HTTP POST to a REST service passing json through C#) the same problem seems to appear. Using Fiddler was suggested.

Using Postman and x-www-form-urlencoded:

POST http://myHost/api/getText HTTP/1.1
Host: myHost
Connection: keep-alive
Content-Length: 29
Cache-Control: no-cache
Origin: chrome-extension://fdmmgilgnpjigdojojpjoooidkmcomcm
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/537.36
Content-Type: application/x-www-form-urlencoded
Accept: */*
Accept-Encoding: gzip,deflate
Accept-Language: nl-NL,nl;q=0.8,en-US;q=0.6,en;q=0.4

question_8=foo&question_9=bar

Using Postman and form-data:

POST http://myHost/api/getText HTTP/1.1
Host: myHost
Connection: keep-alive
Content-Length: 244
Cache-Control: no-cache
Origin: chrome-extension://fdmmgilgnpjigdojojpjoooidkmcomcm
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/537.36
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryvb4wmaP4KooT6TFu
Accept: */*
Accept-Encoding: gzip,deflate
Accept-Language: nl-NL,nl;q=0.8,en-US;q=0.6,en;q=0.4

------WebKitFormBoundaryvb4wmaP4KooT6TFu
Content-Disposition: form-data; name="question_8"

foo
------WebKitFormBoundaryvb4wmaP4KooT6TFu
Content-Disposition: form-data; name="question_9"

bar
------WebKitFormBoundaryvb4wmaP4KooT6TFu--

Using my C#-application:

POST http://myHost/api/getText/ HTTP/1.1
Accept: application/json
Content-Type: application/json; charset=utf-8
Host: myHost
Content-Length: 50
Expect: 100-continue
Connection: Keep-Alive

{"question_8":"foo","question_9":"bar"}

The C# application is sending it clearly in a different way.

2

There are 2 answers

2
Paul Meems On BEST ANSWER

I've found the problem.

Because I use client.PostAsJsonAsync() the POST data is send as json, as you can see in Fiddler.

PHP doesn't expects the POST data to be in json format. To read that data I need to use $data = file_get_contents('php://input'); in my PHP file.

Now I have my keys and values and can I continue. It looks like PHP needs a $_JSON variable ;)

0
Grisgram On

In case, someone else stumbles across this, I made this little loop at the top of my index.php file, which gets POST-called from C#. It restores the $_POST variable from the string in php://input, but only if $_POST is empty

if (count($_POST) == 0) {
    try {
        $copy = json_decode(file_get_contents('php://input'), true);
        foreach($copy as $k => $v) 
            $_POST[$k] = $v;
    } catch (exception $e) {
        // do nothing
    }
}