猿问

如何在不使用 CURL 的情况下发布 api 调用

我尝试以下代码在任何函数中运行我的 cron 但它不起作用


$url = "http://example.com";


    $header = array(

        "Content-type" => "application/json",

        "x-user-agent"=> "shkasdksajd"

    );


    $context_options = array(

        'http' => array(

            'method' => 'POST'

            , 'header' => $header

           

        )

    );


    $context = stream_context_create($context_options);

    $page = file_get_contents($url, false, $context);

    echo $page;

它显示内部服务器错误,但它在邮递员上运行


喵喔喔
浏览 172回答 2
2回答

PIPIONE

你可以CURL使用CURLOPT_USERAGENT像那样$curl = curl_init();curl_setopt_array($curl, array(  CURLOPT_URL => "your url",  CURLOPT_RETURNTRANSFER => true,  CURLOPT_ENCODING => "",  CURLOPT_MAXREDIRS => 10,  CURLOPT_TIMEOUT => 0,  CURLOPT_FOLLOWLOCATION => false,  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,  CURLOPT_CUSTOMREQUEST => "POST",  CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13',  CURLOPT_HTTPHEADER => array(    "x-user-agent: your_x-user-agent_key"  ),));可能有帮助吗

慕工程0101907

实际上,使用发送 HTTP POST 请求file_get_contents并不难:正如您所猜测的,您必须使用$context参数。PHP手册中有一个例子,在这个页面:HTTP上下文选项 (引用):$url = "http://myurl.com/";    $postdata = json_encode(        array(            'var1' => 'some content',            'var2' => 'test content'        )    );    $opts = array('http' =>        array(            'method'  => 'POST',            'header'  => 'Content-Type: application/json',            'content' => $postdata        )    );    $context  = stream_context_create($opts);    $result = file_get_contents($url, false, $context);基本上,您必须使用正确的选项创建一个流(该页面上有一个完整列表),并将其用作第三个参数file_get_contents——仅此而已;-)作为旁注:一般来说,为了发送 HTTP POST 请求,我们倾向于使用 curl,它提供了很多选项——但流是 PHP 的优点之一,没有人知道......太糟糕了...... .
随时随地看视频慕课网APP
我要回答