现在,您正在尝试连接到https://authserver.mojang.com。虽然这是您用来进行身份验证的网站,但它不是正确的页面。您需要将端点用于所需的特定任务。对于身份验证,您要使用authenticate endpoint:/authenticate。
也就是说你需要使用的网址是https://authserver.mojang.com/authenticate,而不仅仅是https://authserver.mojang.com。
您还需要将Content-Type 设置为application/json 才能接受您的请求。
根据the errors documentation,只有当您使用错误的方法而不是错误的目标时,您才会得到Method Not Allowed。我希望在这种情况下你会得到Not Found,但我还没有完全测试你的代码,所以它实际上可能会产生不允许的方法。
以下是如何根据this answer by Jamesst20 进行身份验证的示例:
private static String authenticateEndpoint = "https://authserver.mojang.com/authenticate";
public static void main(String[] args) throws Exception {
auth("{\"agent\": { \"name\": \"Minecraft\", \"version\": 1 }, \"username\": \"example\", \"password\": \"password\"}");
}
private static String auth(String data) throws Exception {
URL url = new URL(authenticateEndpoint);
byte[] contentBytes = data.getBytes("UTF-8");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestProperty("Accept-Charset", "UTF-8");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Content-Length", Integer.toString(contentBytes.length));
OutputStream requestStream = connection.getOutputStream();
requestStream.write(contentBytes, 0, contentBytes.length);
requestStream.close();
String response;
BufferedReader responseStream;
if (connection.getResponseCode() == 200) {
responseStream = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
} else {
responseStream = new BufferedReader(new InputStreamReader(connection.getErrorStream(), "UTF-8"));
}
response = responseStream.readLine();
responseStream.close();
if (connection.getResponseCode() == 200) {
return response;
} else {
// Failed to log in; response will contain data about why
System.err.println(response);
return null;
}
}