亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在不使用 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 關注
  • 166 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號