guzzle和多个异步请求中的多个post xml数据

时间:2016-07-08 15:24:13

标签: php symfony curl timeout guzzle6

如何为多个URI创建异步请求,每个URI具有不同的帖子数据?

我能够获取每个URI的数据,但我想让它异步。

另外,如果请求时间太长,我该如何超时?

我的代码:

//url
$ur1 = 'www.exaample1.com';
$ur2 = 'www.Test.com';
//xml
$ur1_xml = ''; // xml code
$ur2_xml = ''; // xml code
//headers
$ur1_header = array("POST  HTTP/1.1",
        "Content-type: application/xml; charset=\"utf-8\"",
        "Content-length: " . strlen($ur1_xml));
$ur2_header = array("POST  HTTP/1.1",
        "Content-type: application/xml; charset=\"utf-8\"",
        "Content-length: " . strlen($ur2_xml));

       $client = new Client();

    // make request

    $request = new Request('POST', $ur1_url, $ur1_headers,$ur1_xml);
    $promise = $client->sendAsync($request)->then(function ($response) {
        echo '<pre>';
        print_r(simplexml_load_string($response->getBody()));
        echo '</pre>';
    });

 die();

1 个答案:

答案 0 :(得分:0)

对于application/x-www-form-urlencoded发送异步请求,您可以从Guzzle承诺中受益。标题和POST字段应作为documents state进入数组。

use GuzzleHttp\Client;
use GuzzleHttp\Promise;
.
.
.
$client = new Client();
$promises = [
    $client->postAsync($url1, ['headers' => $headers1, 'form_params' => $postData1]),
    $client->postAsync($url2, ['headers' => $headers2, 'form_params' => $postData2]),
    $client->postAsync($url3, ['headers' => $headers3, 'form_params' => $postData3])
];

$results = Promise\unwrap($promises);
$results = Promise\settle($promises)->wait();

// response headers of first request
print_r($results[0]['value']->getHeaders()); 

// retrieved contents of second request
echo $results[1]['value']->getBody()->getContents();