2016-03-02 60 views
0

我想用php cURL調用一些http web服務。當我嘗試在瀏覽器中調用該服務時,我可以提出請求並獲得成功響應。但每當我試着通過捲曲稱呼它,它失敗,錯誤消息:couldn't connect to host我可以通過瀏覽器提交請求,但cURL說無法連接到主機,爲什麼?

我使用這裏的代碼如下:

$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

也許該網站拒絕來自useragent curl的請求?嘗試使用'curl_setopt($ ch,CURLOPT_USERAGENT,「我的用戶代理」)欺騙你的useragent;' – Jordy

回答

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); 

現在它的工作。

1

,如果你有一個基於瀏覽器的HTTP代理服務器設置

+0

我能做些什麼來解決cURL的問題? – mshsayem

+0

請參閱curl,-x,--proxy <[protocol://] [user:password @] proxyhost [:port]>的手冊頁,可以使用我推測 – Bijoy

1

你嘗試設置SSL_VERIFYER爲false這可能發生嗎?

curl_setopt($ ch,CURLOPT_SSL_VERIFYPEER,false);

相關問題