Skip to main content
4 of 4
deleted 1 character in body
TMorgan
  • 311
  • 3
  • 12

drupal_http_request with basic authorization receives 401 response

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?

TMorgan
  • 311
  • 3
  • 12