- 做项目遇到一个需求,就是使用POST发送一些json格式数据、请求一个接口。
- 对于php来说,考虑了以下三种方式,发现第一种和第三种都存在超时的问题,第二种curl相对方便,不必考虑超时问题。
数据:
$data = array('user'=>'test','id'=>'001');
$data = json_encode($data);
接口:
$url = 'http://www.test.com:8080/test';
- 第一种:file_get_contents
- 发现程序没返回,一直阻塞,抓包发现已有正确返回,原因发现是tcp连接没关,没有到超时时间,导致一直没打出来结果,可以创建一个资源句柄,通过控制资源句柄超时来控制file_get_contents这个方法的超时时间。
$aContext = array('http'=>array('method' => 'POST','header' => 'Content-type: application/x-www-form-urlencoded','content' => $data));
$cxContext = stream_context_create($aContext);
$res = file_get_contents($url,true,$cxContext);
- 第二种:curl,正常返回
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HEADER, 0);
$res = curl_exec($ch);
if(curl_errno($ch))
{
echo 'curl error'.curl_error($ch);
}
curl_close($ch);
- 第三种:sock函数
- 发现程序没返,一直阻塞
- 如果服务器没有关闭由 fsockopen() 所打开的连接,feof() 会一直等待直到超时而返回 TRUE。默认的超时限制是 60 秒,可以使用 stream_set_timeout() 来改变这个值。
$sock = fsockopen("10.140.35.11", 8080);
$post_data = "POST http://10.140.35.11/TdnsRecordConfig HTTP/1.1\r\n";
$post_data .= "Accept: */*\r\n";
$post_data .= "Host: 10.140.35.11\r\n";
$post_data .= "Content-Length: ".strlen($data)."\r\n\r\n";
$post_data .= $data;
fputs($sock, $post_data);
$ret_data = '';
while(!feof($sock))
{
$ret_data .= fgets($sock, 1024);
echo $ret_data;
}