我正在向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'));
但请求失败,我从谷歌收到此错误消息:
Error(18): Unknown parameter in Http request: '------------------------------0f1f2f05fb97 Content-Disposition: form-data; name'. Error(13): No output information to produce,yet compilation was requested.
我查看了标题,并发送了此Content-Type标头:
application/x-www-form-urlencoded; charset=UTF-8; boundary=----------------------------0f1f2f05fb97
不确定添加的边界是否正常?我如何防止这种情况,谷歌似乎不喜欢它?
谢谢,
韦斯利
解决方法
看起来Google的API不支持多部分/表单数据数据.这对我来说似乎有点蹩脚……
根据PHP documentation on curl_setopt():
Passing an array to CURLOPT_POSTFIELDS will encode the data as multipart/form-data,
while passing a URL-encoded string will encode the data as application/x-www-form-urlencoded.
$postData = 'output_info=compiled_code&output_format=text&compilation_level=SIMPLE_OPTIMIZATIONS&js_code=' . urlencode($content);
换句话说,您必须自己进行URL编码 – 您显然不能依赖cURL来获取数组并为您编码.