0

I'm trying to post a request using drupal_http_request, but my headers are causing authorization errors.

This is my request:

$headers =  array('Authorization'=>'Bearer [my token here]', 'Content-Type'=>'application/json' );
$url = "https://api.ionic.io/push/notifications";
$message= new stdClass();
$message->message='That works';
$message->title='titleofmessage';
$data = array('tokens' => array('DEV-f765ac70-1bcb-4e0f-8bfd-adfd9612f185'), 'profile'=>'fake_push_profile', 'notification'=>$message);
$result=drupal_http_request($url, $headers, 'POST', json_encode($data));

In cURL it works fine, but I want to use drupal_http_request:

curl -X POST -H "Content-Type: application/json" -H "Authorization: Bearer [my token here]" -d '{"tokens": ["DEV-f765ac70-1bcb-4e0f-8bfd-adfd9612f185"],"profile": "fake_push_profile","notification": {"message": "That works", "title": "titleofmessage"}}' "https://api.ionic.io/push/notifications"

The error message I get is 'Authorization header is missing' so something seems to be happening to that header.

Any help much appreciated!

2 Answers 2

2

You have the second param to drupal_http_request wrong; it should be an array of options, not an array of headers. Headers is just one of those options.

To fix:

$result = drupal_http_request($url, array('headers' => $headers), 'POST', json_encode($data));
1
  • 1
    Thanks Clive. You are right, but it still didn't work for me. That made me recheck the documentation for drupal_http_request and it seems i've been using the drupal 6 notation. My request should have been $options=array('headers'=>$headers, 'data'=>json_encode($data), 'method'=>'POST'); $result=drupal_http_request($url, $options);
    – gillarf
    Mar 5, 2016 at 15:58
1

While Clive was right for Drupal 6, I am using Drupal 7. I've marked his answer as correct, but the code I ended up using was:

$headers =  array('Authorization'=>'Bearer [my token here]', 'Content-Type'=>'application/json' );
$url = "https://api.ionic.io/push/notifications";
$message= new stdClass();
$message->message='That works';
$message->title='titleofmessage';
$data = array('tokens' => array('[device token]'), 'profile'=>'fake_push_profile', 'notification'=>$message);

$options=array('headers'=>$headers, 'data'=>json_encode($data), 'method'=>'POST');

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

Your Answer

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

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