我试图用php cURL调用一些http web服务。当我尝试在浏览器中调用该服务时,我可以发出请求并获得成功响应。但每当我尝试通过cURL调用它时,它都会失败并显示错误消息:couldn't connect to host
我在这里使用的代码如下:
$url = 'http://myserviceurl.com';
$fields = array(
'field1' => urlencode('field1value'),
'field2' => urlencode('field2value'),
'field3' => urlencode('field3value')
);
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');
$ch = curl_init();
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
$result = curl_exec($ch);
if($result === false)
{
echo sprintf('<span>%s</span>CURL error:',curl_error($ch));
return;
}
如何修复/诊断?
答案 0 :(得分:1)
如果您有基于浏览器的http代理集
,则可能会发生这种情况答案 1 :(得分:1)
您是否尝试将SSL_VERIFYER设置为false?
curl_setopt($ ch,CURLOPT_SSL_VERIFYPEER,false);
答案 2 :(得分:0)
@Bijoy(在另一个答案中)是正确的。浏览器中有一个代理集。我更改了代码以使用CURLOPT_PROXY
添加代理,如下所示:
$proxy = '<my-proxy-ip>:<proxy-port>';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_PROXY, $proxy);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
$result = curl_exec($ch);
现在可行。