Powered By Blogger

Thursday, February 9, 2017

cURL in drupal 8 OR webservice in drupal

https://www.drupal.org/node/1838208


I have used both with good results drupal_http_request() is somewhat simpler to use in my opinion but cURL provides more options.
Here are two sample examples for a custom module.
drupal_http_request();
<?php 

DEFINE(MY_URL, 'http://test.com');

myfunction_init() {

    
  $data = array(
      'my_role' => test,
      'password' => 'test',
      'my_id' => test,
  
    );
    $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(MY_URL, $options);

?>
cURL
<?php

function _custommodule_execute($email, $fname, $lname) {

    $id = '94sdf'; 
    $test = 'asdf343'; 

    $url = 'http://test_urlr';
    $query = sprintf('test1=%s&test2=1&test3=%s&test4=%s&test5=%s&test6=%s', $id, $test, $email, $fname, $lname);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $query);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_MAXREDIRS, 0);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); 
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 

    $result = curl_exec($ch);
    $error = curl_error($ch);

    curl_close($ch);

}
?>

No comments:

Post a Comment