【问题标题】:Convert cURL request to Guzzle PHP将 cURL 请求转换为 Guzzle PHP
【发布时间】:2015-11-02 23:51:45
【问题描述】:

我正在尝试将现有的 cURL 请求转换为 Guzzle 6。这是 cURL 请求。 curl请求的代码是这样的。

$xml = file_get_content('new.xml');

// Initialize handle and set options
$ch = curl_init();

curl_setopt( $ch, CURLOPT_URL,     $this->xml_post_url );//
curl_setopt( $ch, CURLOPT_SSLCERT, $this->sslcert );//
curl_setopt( $ch, CURLOPT_SSLKEY,  $this->sslkey );//
curl_setopt( $ch, CURLOPT_POSTFIELDS, $raw_request );
curl_setopt( $ch, CURLOPT_TIMEOUT, 30 );
curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, 20 );
curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Connection: close') );
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt( $ch, CURLOPT_SSLCERTPASSWD, $this->sslcertpasswd );
curl_setopt( $ch, CURLOPT_SSLKEYPASSWD,  $this->sslkeypasswd );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true ); // capture the response to a string

// give it 3 tries
for ($i=1; $i<=3; ++$i) {

    $raw_response = curl_exec($ch);
    $response_HTTP_CODE = (int) curl_getinfo( $ch, CURLINFO_HTTP_CODE );

    if (200 <= $response_HTTP_CODE and $response_HTTP_CODE < 400) {

        if ($raw_response !== false) {

            curl_close( $ch );
            return $raw_response;

        }

    }
    elseif (500 <= $response_HTTP_CODE and strlen( $raw_response ) > 0) {

        $offset = strpos( $raw_response, '<errortext>');

        if ($offset !== false) {

            curl_close( $ch );
            break;

        }
    }

    sleep( 1 ); // give it a moment
}

curl_close( $ch );

如果可能的话,有没有办法以理智的方式将其转换为 Guzzle 请求,并带有重试选项。

这是我尝试过的

$request = $this->getClient()->post($this->request['endPointUrl'], [
        'body' => $xml,
        'cert' => $this->request['sslCert'],
        'config' => [
            'curl' => [
                CURLOPT_SSLVERSION => CURL_SSLVERSION_TLSv1,
                CURLOPT_SSL_VERIFYHOST => false,
                CURLOPT_SSL_VERIFYPEER => false,
                CURLOPT_RETURNTRANSFER => true
            ]
        ]
    ]);
    $response = $request->send()->xml();

但我得到 cURL 异常。

【问题讨论】:

  • 向我们展示您将其转换为 guzzle 的尝试
  • 用代码编辑你的问题,请不要把它放在cmets中
  • But I am getting cURL exception. - 什么例外?

标签: php curl guzzle guzzle6


【解决方案1】:

好吧,我终于解决了这个问题。我发布我的解决方案,希望它可以帮助某人。

$client = new Client();
$client->setDefaultOption('verify', false);

$response = $client->post($endPointUrl, [
                'body'    => ['file_filed' => $xml],
                'cookies' => true,
                'cert'    => [$sslCert, $sslCertPassword],
                'ssl_key' => [$sslKey, $sslKeyPassword]
            ]);

if (200 === $response->getStatusCode()) {

    $xmlResponse = $response->xml();

} else {

    // do something with error.

}

为了重试,我使用了Guzzle retry subscriber

【讨论】:

    猜你喜欢
    • 2017-01-13
    • 2019-12-17
    • 2017-04-04
    • 1970-01-01
    • 2017-08-03
    • 1970-01-01
    • 2015-06-01
    • 1970-01-01
    • 2017-04-12
    相关资源
    最近更新 更多