使用Guzzle将文件发布到Web服务

Mat*_*lin 5 php curl file-get-contents guzzle

我一直在尝试几个小时来发出一个发送文件的POST请求.

首先尝试了一个简单file_get_contents()的流上下文,似乎没有用.当不同URL上的GET工作时,我从未收到回复.

我在网上搜索了一个HTTP客户端,发现Guzzle在Packagist上下载了400k次; 我决定试用这项技术.记录完好,但是,唉,在发布该死的文件时也会收到错误.

$request = $client
    ->post('/files/')
    ->addPostFields(array('comments' => 'no value'))
    ->addPostFile('file', 'test.doc')
    ->setAuth($this->username, $this->password);
Run Code Online (Sandbox Code Playgroud)

我花了几个小时阅读和搜索网络,发现我有一个"417期望失败"问题.

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>417 Expectation Failed</title>
</head><body>
<h1>Expectation Failed</h1>
<p>The expectation given in the Expect request-header
field could not be met by this server.
The client sent<pre>
    Expect: 100-Continue, 100-Continue
</pre>
</p><p>Only the 100-continue expectation is supported.</p>
</body></html>
Run Code Online (Sandbox Code Playgroud)

在网上搜索了更多内容后,我最终阅读了由Guzzle自动发送的"Expect:100-continue"标题,所以我尝试了:

$request->removeHeader('expect');
Run Code Online (Sandbox Code Playgroud)

我现在最终得到了一个糟糕的请求:

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>400 Bad Request</title>
</head><body>
<h1>Bad Request</h1>
<p>Your browser sent a request that this server could not understand.<br />
Request header field is missing ':' separator.<br />
<pre>
zzle/3.7.3 curl/7.15.5 PHP/5.3.27</pre>
</p>
</body></html>
Run Code Online (Sandbox Code Playgroud)

打印请求标头以找到:丢失,我得到:

var_dump($request->__toString());

POST /files/ HTTP/1.1
Host: nunc57.qc.bell.ca
User-Agent: Guzzle/3.7.3 curl/7.15.5 PHP/5.3.27
Content-Type: multipart/form-data
Authorization: Basic bm92YTpzeW5hcHNl
Run Code Online (Sandbox Code Playgroud)

现在我真的很难过,我希望有人已经找到了解决这个问题的方法.我真的厌倦了这一切:(

hal*_*fer 4

我想知道发布到/files/(带有尾部斜杠)是否可能会导致问题。也许这会强制进行内部重定向并让 Goutte 感到不安,但不会让 Web 浏览器感到不安?我会尝试调整您的页面,以便您可以发布到/files/files/something

如果您可以使用网络浏览器 POST 到目标 URL,我还建议您使用浏览器工具记录请求标头,并查看是否有任何标头可以添加到您的 Guzzle 请求中。