簡體   English   中英

PHP:使用 file_get_contents 訪問 API - 空響應

[英]PHP: Using file_get_contents to access an API - Empty Response

很抱歉提前為凌亂的代碼。 我想編寫一個代碼,從官方暴雪 API 返回我的信息,然后我可以在我的主頁上打印出來。 代碼不會拋出任何錯誤,但也不會打印出任何內容。 對於初學者:

  1. 我也更喜歡使用 CURL,但我的主頁在 Wordpress 托管站點上,我不知道如何以這種方式安裝 CURL 庫

  2. allow_furl_open 已開啟

     $url = "https://eu.battle.net/oauth/token"; $data = array('grant_type' => 'client_credentials'); //HTTP options $opts = array('http' => array( 'method' => 'POST', 'header' => array ('Content-type: multipart/form-data', 'Authorization: Basic ' . base64_encode("$client_id:$client_pass")), 'content' => json_encode($data) ) ); //Do request $context = stream_context_create($opts); $json = file_get_contents($url, false, $context); $result = json_decode($json, true); $accessToken = $json['access_token']; $tokenURL = "https://us.api.blizzard.com/data/wow/token/?namespace=dynamic-eu"; $opts2 = array('http' => array( 'method' => 'POST', 'header' => array('Content-type: multipart/form-data', 'Authorization: Bearer ' . $accessToken), ) ); $context2 = stream_context_create($opts2); $json2 = file_get_contents($tokenURL,false,$context2); $result2 = json_decode($json2, true); $tokenprice = $result2['price']; echo "<p>Tokenpreis:" .$tokenprice. "</p>";

我沒有將 $client_id 和 $client_pass 添加到代碼片段中,但這顯然存在。 我使用這個PHP CURL Snippet作為模板。 這是暴雪網站上關於它應該如何工作的簡短解釋:

在此處輸入圖片說明

任何人都知道出了什么問題? 我在這里真的沒有想法,並且會喜歡任何可以提供幫助的人。

提前致謝

根據鏈接的 API 文檔中的 curl 示例,內容類型應為application/x-www-form-urlencoded ,因此對於https://eu.battle.net/oauth/token的初始請求,您應該能夠按照這里的例子。

在您的情況下,這將類似於:

$url = 'https://eu.battle.net/oauth/token'; 

$data = array('grant_type' => 'client_credentials');

$opts = array(
  'http' => array(
    'method' => 'POST',
    'header' => array (
      'Content-type: application/x-www-form-urlencoded',
      'Authorization: Basic ' . base64_encode("$client_id:$client_pass")
    ),
    'content' => http_build_query($data)
  )
);

$context = stream_context_create($opts);

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

此外,在您的代碼中,您將初始請求的原始結果存儲在$json ,然后將解碼后的數組存儲在$result ,但嘗試從初始請求中獲取access_token ,而不是解碼后的數組。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM