php - Guzzle 的行为不像 CURL

标签 php curl guzzle6

我想从纯 CURL 迁移到 Guzzle,但 API 调用未正确注册。

工作 CURL(来自这里的类:https://stackoverflow.com/a/7716768/8461611)

...
$Curl = new CURL(); // setting all curl_opts there

// creating session
$session = explode(";", $Curl->post("http://www.share-online.biz/upv3_session.php", "username=".$un."&password=".$pw));
$session_key = $session[0];
$upload_server = $session[1];

// upload
$vars = ... // see below
var_dump(explode(";",$Curl->post($upload_server, $vars))); // works

现在是 Guzzle 的东西

...
$Curl = new GuzzleHttp\Client();
$jar = new GuzzleHttp\Cookie\FileCookieJar("cookie.txt", true);

//creating session

$session = explode(";", $Curl->request('POST', "http://www.share-online.biz/upv3_session.php", 
   ["form_params" => ["username" => $un, "password" => $pw], 'cookies' => $jar])->getBody());
$session_key = $session[0];
$upload_server = $session[1];

$vars = ["username" => $un,
            "password" => $pw,
            "upload_session" => $session_key,
            "chunk_no" => 1,
            "chunk_number" => 1,
            "filesize" => filesize($file),
            "fn" => new CurlFile(realpath($file)),
            "finalize" => 1,
            "name" => "test",
            "contents" => $file,
    ];

var_dump(
    explode(";",$Curl->request(
            'POST', "http://".$upload_server, ["multipart" => [$vars], 'cookies' => $jar])
               ->getBody()));
// outputs *** EXCEPTION session creation/reuse failed - 09-3-2017, 3:05 am ***

我假设我对 cookie 做错了什么。它们被设置为 var_dump($jar); 显示。 API 文档:http://www.share-online.biz/uploadapi

最佳答案

首先,Guzzle 不是 curl,也不能表现得像 curl。唯一需要注意的是它在幕后使用了 curl。

解决方法如下:

use GuzzleHttp\Client;

$client = new Client([
    // Base URI is used with relative requests
    'base_uri' => 'http://www.share-online.biz/',
    'timeout'  => 2.0,
]);


$response = $client->request('POST', 'upv3_session.php', 
   [
      'form_params' => [
             "username" => $un, 
             "password" => $pw
      ]
   ]
);

Use the output of your request like so: 
$code = $response->getStatusCode(); // 200 || 400 | 500 etc
$reason = $response->getReasonPhrase(); 
$body = $response->getBody();

$response = $request->getBody(); //Explicitly cast to string. 
$json_response = json_decode($response); //here the string response has be decoded to json string.

我希望它能帮助其他面临这种情况的人

关于php - Guzzle 的行为不像 CURL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46019928/

相关文章:

php - 使用 jQuery 或 javascript 聚焦 'multiple' HTML 输入字段

PHP 有什么比curl 更快的方法来检查远程图像文件大小大约3000 倍?

php - 使用 PHP Guzzle HTTP 6 发送带有已编码数据的 JSON

linux - 滥用cURL与Redis通信

node.js - 如何使用 fetch 使用 multipart/form-data header 和 FormData 进行 POST

php - 使用 Guzzle6 形成帖子以获取 Azure token 时遇到问题(错误 : AADSTS90014)

php - Guzzle Http 未找到 mailgun

php - Solr 命令不返回 json 输出

php - foreach 循环内的 Mysqli_query

php - PHP 中 SQL 的安全测试数据