how to construct an https POST request with drupal

2020-07-23 05:07发布

问题:

I want to send a POST request to an https server.

$data = 'name=value&name1=value1';

$options = array(
  'method' => 'POST',
  'data' => $data,
  'timeout' => 15,
  'headers' => array('Content-Type' => 'application/x-www-form-urlencoded'),
);

$result = drupal_http_request('http://somewhere.com', $options);

I can't figure out out to implement the https options in the POST example code above.

Can anyone please explain me how to do this? I am quite new to PHP coding with Drupal, and I could definitely use the guidance.

I found that all is needed is to set it in the protocol. So I got to this code.

$data = 'access_token=455754hhnaI&href=fb&template=You have people waiting to play with you, play now!';

$options = array(
  'method' => 'POST',
  'data' => $data,
  'timeout' => 15,
  'headers' => array('Content-Type' => 'application/x-www-form-urlencoded'),
);

$result = drupal_http_request('https://graph.facebook.com/1000721/notifications?', $options);

It still doesn't work. If I post via Firefox with https://graph.facebook.com/1000080521/notifications?access_token=45575FpHfhnaI&href=fb&template=You have people waiting to play with you, play now! it works.

I am probably not constructing the request properly in Drupal.

What am I doing wrong? How can I get my code to work?

回答1:

There is no difference between using drupal_http_request() with a secure connection (https://), or without a secure connection (http://).

PHP must be compiled with support for OpenSSL; otherwise, drupal_http_request() doesn't support secure connections. Apart that, the only issue could be the proxy server not supporting a secure connection.

As side note, you are using https://graph.facebook.com/1000721/notifications? as URL for the request. The question mark should not be part of the URL.

I would also use drupal_http_build_query() to build the data to use for the request.

$data = array(
  'access_token' => '455754hhnaI',
  'href' => 'fb',
  'template' => 'You have people waiting to play with you, play now!'
);

$options = array(
  'method' => 'POST',
  'data' => drupal_http_build_query($data),
  'timeout' => 15,
  'headers' => array('Content-Type' => 'application/x-www-form-urlencoded'),
);

$result = drupal_http_request('https://graph.facebook.com/1000721/notifications', $options);