Search code examples
phphtmlsymfonygoutte

Goutte Post JSON or set cookie


I'm trying to submit a form using Goutte. The form uses jQuery to serialize a form to json and post to an url. After submitting, it updates the browser's cookie.

I either need to:

  1. set the cookie manually in Goutte,
  2. or send the json post through Goutte so it's cookie jar is updated.

I tried using Goutte's addContent method to create a form and then post it, but it's not sent as JSON, just a regular query string.


Solution

  • here's a class method that may serve as example for both JSON and URLencoding with Goutte.

    use Goutte\Client;
    
    class a 
    {
       /**
       * abstract the request content-type behind one single method,
       * since Goutte does not natively support this
       * @param string $method HTTP method (GET/POST/PUT..)
       * @param string $url URL to load
       * @param string $parameters HTTP parameters (POST, etc) to be sent URLencoded 
       *                           or in JSON format.
       * @return \Symfony\Component\BrowserKit\Response
       */
      protected function makeRequest($method, $url, $parameters) {
          $client = new Client();
          if ($this->requestFormat == 'json') {
              return $client->request($method, $url, array(), array(), array('HTTP_CONTENT_TYPE' => 'application/json'), json_encode($parameters));
          } else {
              return $client->request($method, $url, $parameters);
          }
      }
    }