我需要在PHP中重新创建:
curl -X POST --user <username>:<password>
--header "Content-Type: text/plain;charset=utf-8"
--header "Accept: application/json"
--data-binary @<filename>
"https://gateway.watsonplatform.net/personality-insights/api/v3/profile"我得到了这个:
$request_headers = array();
$request_headers[] = 'Content-Type: text/plain;charset=utf-8';
$request_headers[] = 'Content-Language: en';
$request_headers[] = 'Accept-Language: en';
$simple_data = 'washingtonpost by the intelligence community';
curl_setopt_array( $ch2, array(
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $simple_data,
CURLOPT_HEADER => $request_headers,
CURLOPT_USERPWD => 'XXXX:YYYY',
)
);
$response2 = curl_exec( $ch2 );我的代码没有考虑到--data-binary部分,但是我不确定如何将其“翻译”成PHP。此外,我是否可以将数据二进制与纯文本( API接受)一起使用,而不是JSON?
发布于 2017-02-21 11:55:12
您所拥有的已经是--data-binary的等价物。请参阅CURLOPT_POSTFIELDS API docs
您必须确保数据的格式符合服务器接收数据的要求。libcurl不会以任何方式对其进行转换或编码。
将其与docs for the command-line --data-binary option进行比较
这将完全按照指定的方式发布数据,而不需要任何额外的处理。
至于你问题的第二部分:
JSON是否可以使用纯文本数据二进制(
接受)而不是JSON
是的,无论是从命令行的--data-binary还是从应用程序接口的CURLOPT_POSTFIELDS都是如此。
发布于 2020-12-10 00:34:10
如果您将CURLOPT_POSTFIELDS的值设置为数组(如果您使用CURLFile it 将 be设置为数组),则帖子将被格式化为多部分,从而破坏data-binary部分。
我没有找到一种没有multipart/form-data副作用的使用CURLFile的方法……
我使用的是这个,但它使用的是file_get_contents,它对内存不是很友好(它会在内存中加载整个文件):
<?php
$file_local_full = '/tmp/foobar.png';
$headers = array(
"Content-Type: application/octet-stream", // or whatever you want
);
// if the file is too big, it should be streamed
$curl_opts = array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_HTTPHEADER => $headers,
CURLOPT_POSTFIELDS => file_get_contents($file_local_full),
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1
);
// echo "curl_opts:\n" . print_r($curl_opts, true) . "\n"; exit;
$curl = curl_init();
curl_setopt_array($curl, $curl_opts);
$response = curl_exec($curl);发布于 2020-12-10 06:24:51
好了,我已经找到了一种不用multipart/form-data就可以流式上传的方法,关键是欺骗curl,首先我们告诉他PUT,然后发布:
<?php
$file_local_full = '/tmp/foobar.png';
$content_type = mime_content_type($file_local_full);
$headers = array(
"Content-Type: $content_type", // or whatever you want
);
$filesize = filesize($file_local_full);
$stream = fopen($file_local_full, 'r');
$curl_opts = array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_PUT => true,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_HTTPHEADER => $headers,
CURLOPT_INFILE => $stream,
CURLOPT_INFILESIZE => $filesize,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1
);
$curl = curl_init();
curl_setopt_array($curl, $curl_opts);
$response = curl_exec($curl);
fclose($stream);
if (curl_errno($curl)) {
$error_msg = curl_error($curl);
throw new \Exception($error_msg);
}
curl_close($curl);致词:How to POST a large amount of data within PHP curl without memory overhead?
https://stackoverflow.com/questions/42358104
复制相似问题