我想知道这是否有可能在PHP中使用curl或file_get_contents。
我有一些Python代码:
body = json.dumps({
'agent': {
'name': 'Minecraft',
'version': 1
},
'username': email,
'password': password,
'clientToken': "fff"
})
r = requests.post(url="https://authserver.mojang.com/authenticate", headers=header, data=body)CURL中的等价物是什么?因为我已经尝试了PHP的一些变体,但是不能让它工作。
PHP代码,我已经尝试过:
$parameters = [
'agent' => [
'name' => 'Minecraft',
'version' => 1
],
'username' => $email,
'password' => $password,
'clientToken' => 'fff'
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"https://authserver.mojang.com/authenticate");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$parameters); //Post Fields
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$headers = array(
'Accept: application/json',
'Content-Type: application/json',
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close ($ch);但我得到的回应是:
{"error":"JsonParseException","errorMessage":"Unexpected character ('-' (code 45)) in numeric value: expected digit (0-9) to follow minus sign, for valid numeric value\n at [Source: (org.eclipse.jetty.server.HttpInputOverHTTP); line: 1, column: 3]"}如果任何人对此有任何见解,请在这个问题上回复!
发布于 2021-04-22 06:37:25
您的问题在于身份验证对象的创建。您正在创建一个PHP数组(您需要一个对象),并且在发送之前不会转换为JSON。
将身份验证对象创建为对象,然后使用json_encode()创建一个JSON字符串,并将其用作有效负载。
<?php
// Display some error s for this development code
error_reporting(E_ALL);
ini_set('display_errors',1);
// Create the authentication object
$params = (object)[];
$params->agent = (object)['name'=>"MineCraft", 'version'=>'1'];
$params->username = "email";
$params->password='password';
$params->clientToken='fff';
// Now create the payload for cURL to use in its POST
$payload = json_encode($params);
// Set headers to match payload
$headers = array(
'Accept: application/json',
'Content-Type: application/json',
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"https://authserver.mojang.com/authenticate");
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$payload); //Post Fields
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$curlInfo = curl_getinfo($ch);
curl_close ($ch);
// Ok - see what we got.
echo "----------------------------<br>\n";
var_dump($response);
echo "----------------------------<br>\n";
var_dump($curlInfo);下面的代码给出了这样的结果:
{"error":"ForbiddenOperationException","errorMessage":"Invalid credentials. Invalid username or password."}因为我在Mojang没有用户名或密码,所以这是我所期望的
https://stackoverflow.com/questions/67203961
复制相似问题