Guzzle表现得不像CURL

时间:2017-09-03 03:12:17

标签: 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

2 个答案:

答案 0 :(得分:0)

首先,食嘴不是卷曲的,不能表现得像卷曲。唯一的警告是它在后台使用了卷曲。

这是解决方案:

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.

我希望它可以帮助其他面对这种情况的人

答案 1 :(得分:-1)

首先,您必须致电...->getBody()->getContents()以获取字符串。或者将正文对象转换为字符串:(string) ...->getBody()

然后,您无法使用CurlFile课程。使用fopen()获取文件句柄并将其直接传递给Guzzle,如in the docs。请注意,对于文件上传,您必须使用multipart而不是form_params