Use httpClient - Guzzle for Drupal 8 custom module

I am developing a special Drupal 8 module. I have two fields (url and text html fields) in any node type. These are the functions expected by the module:

The module will clear the page "URL fields" and copy the html code to paste them into the "text html" field (this field is hidden on the admin page). Each time cron starts, this field content will be crushed.

Im using Drupal::httpClient(or Guzzle) to make my http request.

$client = \Drupal::httpClient();
$request = $client->get('https://github.com/codeafrica/github-africa');
$response = $request->getBody();

This is my first Drupal 8 development module. To develop this module, do I need to create a custom Http client to create my own Http client? If in my modular repertoires I have to implement the functions of copying and pasting html code. Can a controller do this?

This is the structure of my custom module:

custom_module.info.yml
custom_module.module
custom_module.routing.yml
src/Controller
src/Http  

I need a guide to get started. Thank you for your help.

+4
source share
1 answer

I came across this question when I was working on something similar, so I share the two ways that I was able to get this to work.

I'm not sure if any of them is the best way :)

In my custom_module.module:

  • Method 1

    $client = new \GuzzleHttp\Client();
    $url = 'yourURL';
    $res = $client->request('GET', $url);
    $res_body = $res->getBody();
    
  • or method 2

    use Guzzle\Http\Client;
    $client = new Client('yourURL');
    

0
source

Source: https://habr.com/ru/post/1660029/


All Articles