当前位置: 代码迷 >> PHP >> 使用curl post数据有关问题
  详细解决方案

使用curl post数据有关问题

热度:106   发布时间:2016-04-29 01:21:36.0
使用curl post数据问题
最近遇到一个很奇怪的问题
在发送post请求时,如果POSTFIELDS的类型为string的话,就会超时,但类型为array就没问题。
PHP code
$ch = curl_init();curl_setopt($ch, CURLOPT_URL, $url);curl_setopt($ch, CURLOPT_POST, true);// 数据为string类型时,超时;// 如果是array('param' => $data_string)就没问题。curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);curl_setopt($ch, CURLOPT_TIMEOUT, 3);curl_exec($ch);curl_close($ch);


------解决方案--------------------
传递一个数组到CURLOPT_POSTFIELDS,cURL会把数据编码成 multipart/form-data,而然传递一个URL-encoded字符串时,数据会被编码成 application/x-www-form-urlencoded。
这是它们唯一的区别,超时是网络因素我觉得,和代码无关
另外你的TIMEOUT调的的确有点小了,超时就像家常便饭
------解决方案--------------------
那你的string是什么?
------解决方案--------------------
网上找些列子看看,是不是用法不对。如果都正确,只能说明是其它原因导致的

http://hi.baidu.com/chenxiandong1988/blog/item/56f3b0282bd0fde6e7cd4087.html
------解决方案--------------------
我用你的代码在本地试了一下,并没有发现问题。
PHP code
$data_string = "ispost=ok&msg=post";$data = array("ispost"=>"ok","msg"=>"post");$ch = curl_init();curl_setopt($ch, CURLOPT_URL, "http://localhost/my/www/getdata.php");curl_setopt($ch, CURLOPT_POST, true);curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);curl_setopt($ch, CURLOPT_TIMEOUT, 30);$result = curl_exec($ch);curl_close($ch);echo $result;
  相关解决方案