1

I am trying to use drupal_http_request to connect to a remote rest-based webservice that uses http basic authorization. The following curl command works every time from a command line, and I'm trying to figure out how to do the same the "drupal 7 way".

    curl 'https://XXXXXXXX/login' -H 'Authorization: Basic XXXXXXXX==' \
      -H 'Content-Type: application/x-www-form-urlencoded' \
      --data 'username=XXXXXXXX&password=XXXXXXXX'

Here is the code I am using in Drupal

    class XXXXXX {
      function login($username='', $password='') {
        // construct url - returns https://XXXXXXXX/login
        $url = $this->constructLoginUrl();

        $data = array(
          'username' => $username,
          'password' => $password
        );

        $headers = array(
          'Authorization' => "Basic XXXXXXXX==",
          'Content-Type'  => "application/x-www-form-urlencoded"
        );

        $response = drupal_http_request( $url, $headers, 'POST', http_build_query( $data )     

        return $response;
      }
    }

When I run the curl request, I get a json_encoded response. When I run the second bit of code, I get a 401 unauthorized error from the other server. So, my intent is to make the Drupal request work exactly the same as the curl request above. Is there something I should be doing differently?

1 Answer 1

4

If you're using Drupal 7, then I'm fairly certain you're supposed to put everything after the URL into a single options array instead of positional arguments. This was done so you can pass some arguments without passing all of the preceding ones.

https://api.drupal.org/api/drupal/includes!common.inc/function/drupal_http_request/7

drupal_http_request($url, array(
  'headers' => $headers,
  'method' => 'POST',
  'data' => http_build_query($data)
));

should work.

0

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.