php curl 設置請求頭headers和請求體body

啥也不說,直接上代碼。php

我這裏是post請求。json

$url = "http://www.example.com";
//headers數組內的格式
$headers = array();
$headers[] = "app-id:xxxxx";
$headers[] = "Content-Type:application/json";
$body   = array(
            "username" => "username",
            "password" => "password"
       );
$postBody    = json_encode($body);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);//設置請求頭
curl_setopt($curl, CURLOPT_POSTFIELDS, $postBody);//設置請求體
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');//使用一個自定義的請求信息來代替"GET"或"HEAD"做爲HTTP請求。(這個加不加沒啥影響)
$data = curl_exec($curl);
echo $data;
相關文章
相關標籤/搜索