PHP:使用file_get_内容访问API空响应
对不起,我事先把代码弄乱了。我想写一段代码,从官方暴雪API返回信息,然后在我的主页上打印出来。代码不会抛出任何错误,但也不会打印出任何内容。首先:PHP:使用file_get_内容访问API空响应,php,api,file,Php,Api,File,对不起,我事先把代码弄乱了。我想写一段代码,从官方暴雪API返回信息,然后在我的主页上打印出来。代码不会抛出任何错误,但也不会打印出任何内容。首先: 我也更喜欢使用CURL,但我的主页位于Wordpress托管网站上,我不知道如何以这种方式安装CURL库 “允许卷取”打开 $url = "https://eu.battle.net/oauth/token"; $data = array('grant_type' => 'client_credentials')
$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>";
$url=”https://eu.battle.net/oauth/token";
$data=array('grant_type'=>'client_-credentials');
//HTTP选项
$opts=array('http'=>
排列(
'方法'=>'发布',
'header'=>array('Content-type:multipart/formdata','Authorization:Basic'。
base64_编码(“$client_id:$client_pass”),
'content'=>json_encode($data)
)
);
//请求
$context=stream\u context\u create($opts);
$json=file\u get\u contents($url,false,$context);
$result=json_decode($json,true);
$accessToken=$json['access_token'];
$tokenURL=”https://us.api.blizzard.com/data/wow/token/?namespace=dynamic-欧盟”;
$opts2=数组('http'=>
排列(
'方法'=>'发布',
'header'=>array('Content-type:multipart/formdata','Authorization:Bearer'.$accessToken),
)
);
$context2=stream\u context\u create($opts2);
$json2=file\u get\u contents($tokenURL,false,$context2);
$result2=json_decode($json2,true);
$tokenprice=$result2['price'];
echo“Tokenpreis:”.$tokenprice。“”;
提前感谢基于链接API文档中的curl示例,内容类型应为
application/x-www-form-urlencoded
,因此对于向您发出的初始请求,您应该能够遵循该示例
在您的情况下,这将类似于:
$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
中,但尝试从初始请求而不是解码数组中获取访问令牌。您确定正确的HTTP方法吗?@Sibidharan Hi感谢您的快速回答,我还认为GET更有意义,但是所有访问暴雪API的代码片段都使用POST(如上面提到的链接)。我还用GET-through测试了它,它没有改变任何东西是的,但它没有改变任何东西内容类型:多部分/表单数据?