【问题标题】:Multiple post xml data in guzzle and multiple async requestguzzle 中的多个 post xml 数据和多个异步请求
【发布时间】:2016-11-11 05:42:48
【问题描述】:

如何创建对多个 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();

【问题讨论】:

    标签: php symfony curl timeout guzzle6


    【解决方案1】:

    对于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();
    

    【讨论】:

    • 我之前尝试过使用上面的代码,但我得到`错误:调用非对象上的成员函数getHeaders()`
    • 也是它的“body”而不是“form_params”
    • form_params 是按照Guzzle's doc 将 POST 字段附加到请求的正确方法。但是由于您在getHeaders() 上遇到的错误,我更新了我的答案。请检查@PeterHahn
    • 两件事:1. $postData 应该有body 索引。 2. 我认为这只是 application/x-www-form-urlencoded 的 HTTP Post。我有 3 个 RestAPI 和 4 个 SOAP API,有些需要应用程序/xml、应用程序/json、应用程序/文本。我收到客户端错误 415,即不支持的媒体格式
    • 我已经使用 curl_multi 成功实现了,但是代码很长,大约 200 行,尽管我已经为每个 ApI 分离了正文、标题,然后 curl 多处理使其非常长。快速谷歌搜索建议 Guzzle
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-24
    • 2019-09-16
    • 2015-01-17
    • 2012-05-26
    • 2018-04-10
    • 1970-01-01
    相关资源
    最近更新 更多