我正在嘗試使用curl呼叫一個API(直接從我的應用程式的后端)。這是我第一次使用它,所以我仔細研究了一下,以了解如何做到這一點。 檔案中說這是一個請求:
curl --location -g --request POST '{{url}}/api/rest/issues/'/span>
--header 'Authorization: {{token}}'
--header 'Content-Type: application/json'/span>
--data-raw '{
"摘要": "這是一個測驗問題"。
"描述": "這是一個測驗描述"。
"類別": {
"名稱": "一般"
},
"專案": {
"名稱": "project1"
}
}'
如果我從終端執行它,這應該是代碼(如果我得到它是正確的)。如果我想在一個php腳本中移動執行它,我必須把它轉換為類似的東西:
$pars=array(
'nome' => 'pippo',
'cognome' => 'disney',
'email' => '[email protected]',
);
//步驟1
$curlSES=curl_init()。
//step2
curl_setopt($curlSES,CURLOPT_URL,"http://www.miosito.it"/span>)。
curl_setopt($curlSES,CURLOPT_RETURNTRANSFER,true)。
curl_setopt($curlSES,CURLOPT_HEADER, false)。
curl_setopt($curlSES, CURLOPT_POST, true)。
curl_setopt($curlSES, CURLOPT_POSTFIELDS,$pars) 。
curl_setopt($curlSES, CURLOPT_CONNECTTIMEOUT,10) 。
curl_setopt($curlSES, CURLOPT_TIMEOUT,30) 。
//step3
$result=curl_exec($curlSES)。
//step4
curl_close($curlSES)。
//step5
echo $result;
我將根據我的需要進行調整。這樣做正確嗎?是否有其他方法可以讓它像檔案中的curl請求一樣簡單?
uj5u.com熱心網友回復:
我會使用像Guzzle的HTTP客戶端。
$client = new GuzzleHttpClient() 。
$response = $client->request('POST'/span>, 'http://www.miosito.it'/span>, [
'form_params' => ['form_params' =>
'nome' => 'pippo'。
'cognome' => 'disney',
'email' => '[email protected]',
]
]);
echo (string) $response->getBody()。
uj5u.com熱心網友回復:
有幾種方法來做curl。你的代碼看起來不錯,你也可以試試我的代碼。
$pars=array(
'nome' => 'pippo',
'cognome' => 'disney',
'email' => '[email protected]',
);
如果有時你需要發送json編碼的引數,那么請使用下面這行。
// $post_json = json_encode($pars);
Curl代碼如下所示
$apiURL = 'http://www.miosito.it'。
$ch = @curl_init()。
@curl_setopt($ch, CURLOPT_POST, true)。
@curl_setopt($ch, CURLOPT_POSTFIELDS, $pars) 。
@curl_setopt($ch, CURLOPT_URL, $apiURL) 。
@curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')) 。
@curl_setopt($ch, CURLOPT_RETURNTRANSFER, true)。
$response = @curl_exec($ch)。
$status_code = @curl_getinfo($ch, CURLINFO_HTTP_CODE)。
$curl_errors = curl_error($ch)。
@curl_close($ch)。
echo "<br> Curl Errors: " 。$curl_errors;
echo "<br>狀態代碼。" 。$status_code;
echo "<br> Response: " 。$response。
如果你有其他需要,請告訴我。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/319758.html
標籤:
