php curl 设置请求头headers和请求体body

啥也不说,直接上代码。

我这里是post请求。

$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;
啥也不说,直接上代码。 我这里是post请求。 $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;
经验分享 程序员 微信小程序 职场和发展