为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
喵喔喔 2022-10-28 14:18:35
我尝试以下代码在任何函数中运行我的 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;它显示内部服务器错误,但它在邮递员上运行
查看完整描述

2 回答

?
PIPIONE

TA贡献1829条经验 获得超9个赞

你可以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"

  ),

));

可能有帮助吗


查看完整回答
反对 回复 2022-10-28
?
慕工程0101907

TA贡献1887条经验 获得超5个赞

实际上,使用发送 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 的优点之一,没有人知道......太糟糕了...... .


查看完整回答
反对 回复 2022-10-28
  • 2 回答
  • 0 关注
  • 171 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号