Wes*_*ley 4 php curl http http-headers google-closure-compiler
我正在向google封闭编译器API服务发出请求:
$content = file_get_contents('file.js');
$url = 'http://closure-compiler.appspot.com/compile';
$post = true;
$postData = array('output_info' => 'compiled_code', 'output_format' => 'text', 'compilation_level' => 'SIMPLE_OPTIMIZATIONS', 'js_code' => urlencode($content)));
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
if ($post) {
curl_setopt($ch, CURLOPT_POST, $post);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
}
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded; charset=UTF-8'));
Run Code Online (Sandbox Code Playgroud)
但请求失败,我从谷歌收到此错误消息:
Error(18): Unknown parameter in Http request: '------------------------------0f1f2f05fb97
Content-Disposition: form-data; name'.
Error(13): No output information to produce, yet compilation was requested.
Run Code Online (Sandbox Code Playgroud)
我查看了标题,并发送了此Content-Type标头:
application/x-www-form-urlencoded; charset=UTF-8; boundary=----------------------------0f1f2f05fb97
Run Code Online (Sandbox Code Playgroud)
不确定添加的边界是否正常?我如何防止这种情况,因为谷歌似乎不喜欢它?
谢谢你,韦斯利
您必须http_build_query()在将POST数据(数组)发送到cURL之前使用.
string http_build_query ( mixed $query_data [, string $numeric_prefix [, string $arg_separator [, int $enc_type = PHP_QUERY_RFC1738 ]]] )
Run Code Online (Sandbox Code Playgroud)
所以你$postData应该看起来像这样:
$postData = http_build_query(
array(
'output_info' => 'compiled_code',
'output_format' => 'text',
'compilation_level' => 'SIMPLE_OPTIMIZATIONS',
'js_code' => urlencode($content)
)
);
Run Code Online (Sandbox Code Playgroud)
看起来Google的API不支持多部分/表单数据数据.这对我来说似乎有点蹩脚......
将数组传递给CURLOPT_POSTFIELDS会将数据编码为multipart/form-data,而传递URL编码的字符串会将数据编码为application/x-www-form-urlencoded.
因此,如果您将代码的第4行更改为以下内容,它应该可以工作:
$postData = 'output_info=compiled_code&output_format=text&compilation_level=SIMPLE_OPTIMIZATIONS&js_code=' . urlencode($content);
Run Code Online (Sandbox Code Playgroud)
换句话说,您必须自己进行URL编码 - 您显然不能依赖cURL来获取数组并为您编码.
| 归档时间: |
|
| 查看次数: |
1448 次 |
| 最近记录: |