2

如何为每个具有不同发布数据的多个 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();
4

1 回答 1

1

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

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();
于 2016-07-12T10:37:47.697 回答