2

I need to send asynchronous and non-blocking POST HTTP requests from a Drupal service.

Using Drupal 7, I used HTTP Parallel Request which worked fine.

But this module is not available on Drupal 8. And it seems that the default D8 HTTP Client, Guzzle, doesn't allow to do this : https://stackoverflow.com/questions/35956516/send-asynchronous-request-without-waiting-the-response-using-guzzle.

Is there some way I can achieve that with Drupal 8 ?

Edit: If I don't find how to do it with Drupal mechanisms, I will go with this fsockopen...

1 Answer 1

2

I ended up implementing a custom function on the base of this post :

private function async( $method, $url, $params = array() ){
    // Get URL parts
    $url_parts = parse_url( $url );

    // If needed, append params to query url
    if( $method === 'GET' ){
        $url .= '?' . http_build_query( $params );
    }

    // Open socket
    $port = isset( $url_parts['port'] ) ? $url_parts['port'] : 80;
    $fp = fsockopen( $url_parts['host'], $port, $errno, $errstr, 30 );

    // Build HTTP request
    $request = $method." ".$url." HTTP/1.1\r\n";
    $request.= "Host: ".$url_parts['host'].":".$port."\r\n";
    $request.= "Connection: Close\r\n";
    if( $method === 'POST' || $method === 'DELETE' ){
        $post_string = Json::encode( $params );
        $request.= "Content-Type: application/json; charset=utf-8\r\n";
        $request.= "Content-Length: ".strlen( $post_string )."\r\n";
        $request.= "\r\n";
        if( isset($post_string) ){
            $request.= $post_string;
        }
    } else {
        $request.= "\r\n";
    }

    // Send request and immediately close the pointer
    fwrite($fp, $request);
    fclose($fp);
}

Your Answer

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

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