4

I am having issues sending a POST via my module.

In my browser's REST client I get a 200 with

POST https://mydomain.com 
username=myuser&password=password1

So I know that the service is working fine. I tried to replicate this call in my Drupal module with

$url = "https://mydomain.com";
$data = array(
    'username' => 'myuser',
    'password' => 'password1',
);

$data = http_build_query($data, '', '&');
$options = array(
  'method' => 'POST',
  'data' => $data
);

$response = drupal_http_request($url, $options);

The response I get is a 400. according to this I am not constructing the request correctly.

Question: How should I change my code in order to get a 200?

Note: I am using Drupal 7.

Thanks.

1 Answer 1

4

It's probably that you are missing the Content-Type header, as detailed here. For Drupal 7, this should look like this:

<?php
$response = drupal_http_request(
 'http://www.example.com',
 array('headers' => array('Content-Type' => 'application/x-www-form-urlencoded'),
 'method' => 'POST',
 'data' => 'param1=value1&param2=value2'));
?>
1
  • 1
    If you want a HTTP client that's a little smarter (adds the correct content type and auto http_build_query for data) and and do things in parallel checkout HTTPRL
    – mikeytown2
    Commented May 18, 2012 at 18:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.