drupal_http_request not sending POST data?

If you're used to writing HTTP requests using cURL, developing with Drupal is nice because drupal_http_request does all the work for you without having to pass a long list of options. Let's say that you need to send some data to another server with POST, and you read the documentation for drupal_http_request. A quick glance at the list of options shows that you could do this:


// WRONG WAY TO POST DATA - DRUPAL 7
$response = drupal_http_request($url, array(
    'method' => 'POST',
    'data' => http_build_query($params),
));

However if you run this code you may find that the parameters are not passed to the destination script. What's going wrong? Although it's not obvious if you're used to cURL, it is simple. The default Content-Type for sending POST data is application/x-www-form-urlencoded, and Drupal does not set this for you. A simple header change:


// right way to post data - Drupal 7
$response = drupal_http_request($url, array(
    'method' => 'POST',
    'data' => http_build_query($params), // see comments below - you may need to change this
    'headers' => array('Content-Type' => 'application/x-www-form-urlencoded')
));

And you'll be POSTing data. Note that in this case the destination script was in PHP, and another posting refers to this with a Java server. It depends on the target website; other systems might read the data even without the correct header. This appears to happen in Drupal 6 and 7.

Category: