事例:
今天要向一台服务器上传文件,原版是curl的get模式,现在改用了post模式,按照原本的思想,代码如下
1 <?php 2 $post[‘c‘] = ‘config‘; 3 $post[‘t‘] = ‘show‘; 4 $post[‘o‘] = ‘xml‘; 5 $post[‘ssid‘] = ‘%07o%B4%88O%EE%0Ca%07%DA%D8i%D36HE%AF%28%BC%3C%BE%D5s%DFv%A6%D83%D9%3E%16%96U%B4q%BA%0A%9A%DE%F0%BFJjh%DF2%FF%D2‘; 6 7 8 $curl = curl_init(); 9 curl_setopt($curl, CURLOPT_URL,"http://172.16.59.130:28099/cgi-bin/japi.cgi"); 10 curl_setopt($curl, CURLOPT_POST, true); 11 curl_setopt($curl, CURLOPT_POSTFIELDS, $post); 12 curl_setopt($curl, CURLOPT_ENCODING, "gzip"); 13 curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/537.36 14 Accept-Encoding: gzip,deflate,sdch"); 15 16 curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); 17 curl_setopt($curl, CURLINFO_HEADER_OUT, true); 18 curl_setopt($curl, CURLOPT_FOLLOWLOCATION, false); 19 $contents = curl_exec($curl); 20 curl_close($curl); 21 echo $contents; 22 ?>
但是耗时总是在2s左右,而用get模式则是很快,刚开始怀疑是服务器的问题,但是抱着试试看的态度,查了下curl post有什么特殊的地方,这还真发现了。
在php curl post模式上,启用时会发送一个常规的POST请求,类型为:application/x-www-form-urlencoded,就像表单提交的一样。
如果把要post的数组转换成字符串,像get那种url,速度就上来了
1 <?php 2 $post[‘c‘] = ‘config‘; 3 $post[‘t‘] = ‘show‘; 4 $post[‘o‘] = ‘xml‘; 5 6 $post = http_build_query($post); 7 $post .= "&ssid=%07o%B4%88O%EE%0Ca%07%DA%D8i%D36HE%AF%28%BC%3C%BE%D5s%DFv%A6%D83%D9%3E%16%96U%B4q%BA%0A%9A%DE%F0%BFJjh%DF2%FF%D2"; 8 9 $curl = curl_init(); 10 curl_setopt($curl, CURLOPT_URL,"http://172.16.59.130:28099/cgi-bin/japi.cgi"); 11 curl_setopt($curl, CURLOPT_POST, true); 12 curl_setopt($curl, CURLOPT_POSTFIELDS, $post); 13 curl_setopt($curl, CURLOPT_ENCODING, "gzip"); 14 curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/537.36 15 Accept-Encoding: gzip,deflate,sdch"); 16 17 curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); 18 curl_setopt($curl, CURLINFO_HEADER_OUT, true); 19 curl_setopt($curl, CURLOPT_FOLLOWLOCATION, false); 20 $contents = curl_exec($curl); 21 curl_close($curl); 22 echo $contents; 23 ?>
时间: 2024-10-18 08:09:26