2

我在 Laravel 4 中使用 Guzzle 将文件发送到服务器将处理的远程服务器。但是在将文件发布到服务器时,出现以下异常:

Guzzle \ Http \ Exception \ ClientErrorResponseException
Client error response [status code] 417 [reason phrase] Expectation Failed [url] http://example.com/.....

以下是我正在使用的代码:

use Guzzle\Service\Client as GuzzleClient;
use Guzzle\Plugin\Cookie\Cookie;
use Guzzle\Plugin\Cookie\CookiePlugin;
use Guzzle\Plugin\Cookie\CookieJar\ArrayCookieJar;

$remote_url = 'http://example.com/';
$client = new GuzzleClient($remote_url);
$client->setSslVerification(FALSE);

$cookieJar = new ArrayCookieJar();
// Create a new cookie plugin
$cookiePlugin = new CookiePlugin($cookieJar);
// Add the cookie plugin to the client
$client->addSubscriber($cookiePlugin);

$post_data = array(
            'username' => $input['username'],
            'password' => $input['password'],
        );
$response = $client->post('login', array(), $post_data)->send();
$response_json = $response->json();
if (isset($response_json['error'])) {
    throw new Exception($response_json['error']);
}

$current_time = date("Y-m-d-H-i-s");
$file = 'C:\test\test_file.zip';
$request = $client
                ->post('receiveFile')
                ->addPostFields(array('current_time'=>$current_time))
                ->addPostFile('file', $file)
                ->send();

用户的身份验证似乎工作正常,问题仅在尝试发送文件时才开始。仅当我尝试将文件发送到 Web 服务器时,应用程序才会引发错误。当我尝试将相同的文件发送到本地服务器上的相同应用程序时,我得到了预期的结果,没有任何错误。

我寻找其他人可能遇到的类似问题,并在 SO Posting a file to a web service with Guzzle上找到了一个,但适用于该问题的 OP 的解决方案对我不起作用。我能做些什么来解决这个问题?

4

1 回答 1

2

原来,在发送请求时,请求Expect中添加了一个标头。所以我所做的是Expect在发送请求之前删除标头,并且一切正常。以下是我更改的代码:

$request = $client
            ->post('receiveFile')
            ->addPostFields(array('current_time'=>$current_time))
            ->addPostFile('file', $file)
            ->removeHeader('Expect')
            ->send();

我使用该removeHeader方法删除Expect标题。看起来removeHeader必须在使用该方法之前调用该send方法,因为我在该post方法之前使用过它并且之前没有工作过。

于 2014-03-23T03:40:40.297 回答