我有一段可以上传二进制文件到一个我没有shell访问权限的远程服务器的PHP代码。以下是这段PHP代码:
function upload($uri, $filename) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $uri);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, array('file' => '@' . $filename));
curl_exec($ch);
curl_close($ch);
}
这会导致生成一个类似以下的头部信息:
HTTP/1.1
Host: XXXXXXXXX
Accept: */*
Content-Length: 208045596
Expect: 100-continue
Content-Type: multipart/form-data; boundary=----------------------------360aaccde050
我正在尝试使用requests将此内容转换为Python代码,但是我无法让服务器接受我的POST请求。我已经尝试了各种方法来使用requests.post,但是头部信息无法模仿上述内容。
这会成功地将二进制文件传输到服务器(可以通过观察Wireshark进行判断),但由于头部信息不符合服务器的预期,它被拒绝了。然而,响应代码为200。
files = {'bulk_test2.mov': ('bulk_test2.mov', open('bulk_test2.mov', 'rb'))}
response = requests.post(url, files=files)
请求代码的结果是一个标题:
HTTP/1.1
Host: XXXX
Content-Length: 160
Content-Type: multipart/form-data; boundary=250852d250b24399977f365f35c4e060
Accept-Encoding: gzip, deflate, compress
Accept: */*
User-Agent: python-requests/2.2.1 CPython/2.7.5 Darwin/13.1.0
--250852d250b24399977f365f35c4e060
Content-Disposition: form-data; name="bulk_test2.mov"; filename="bulk_test2.mov"
--250852d250b24399977f365f35c4e060--
有什么想法可以使请求与PHP代码生成的标头匹配吗?
Content-Length
只有160个字节。这恰好是多部分边界、元数据和换行符的大小。你的文件似乎是空的。 - Martijn Pietersres = requests.post(url, data=open_file, headers={'Content-Type':'multipart/form-data; boundary=----------------------------360aaccde050'})
,我得到的Content-Length: 208045390
是准确的。但是头部信息与服务器期望的不同。 - user3524641