我已经尝试过一段时间验证一个Minecraft帐户了,我已经尝试了所有我能想到的或者通过在google上搜索找到的东西。但是无论我尝试什么,我都会得到各种不同的错误,如405或错误的请求。 ..
这是我最新的尝试返回405 |方法不允许:
public class Main {
static String authServer = "https://authserver.mojang.com";
public static void main(String[] args) throws Exception {
auth();
}
//{"agent": { "name": "Minecraft", "version": 1 }, "username": "example", "password": "password"}
static void auth() throws IOException {
URL url = new URL(authServer);
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestMethod("POST");
OutputStreamWriter out = new OutputStreamWriter(
httpCon.getOutputStream());
System.out.println(httpCon.getResponseCode());
System.out.println(httpCon.getResponseMessage());
out.close();
}
}
答案 0 :(得分:1)
目前,您正在尝试连接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基于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;
}
}