问题
I need to figure out a way to check if minecraft username and password is valid.
I have found this documentation which is telling a lot of things about the minecraft authentication : http://wiki.vg/Authentication
Looks like it needs a JSON HTTP POST Request but I have no idea how to do that :S
I have searched a lot and went through a lot of exemple but none of these works. The best result I had is no result printed in console or a 403 error.
Thanks
回答1:
I figured out how to do it !
private static String MakeJSONRequest(String username, String password){
JSONObject json1 = new JSONObject();
json1.put("name", "Minecraft");
json1.put("version", 1);
JSONObject json = new JSONObject();
json.put("agent", json1);
json.put("username", username);
json.put("password", password);
return json.toJSONString();
}
private static String httpRequest(URL url, String content) throws Exception {
byte[] contentBytes = content.getBytes("UTF-8");
URLConnection connection = 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 (((HttpURLConnection) connection).getResponseCode() == 200) {
responseStream = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
} else {
responseStream = new BufferedReader(new InputStreamReader(((HttpURLConnection) connection).getErrorStream(), "UTF-8"));
}
response = responseStream.readLine();
responseStream.close();
if (((HttpURLConnection) connection).getResponseCode() != 200) {
//Failed to login (Invalid Credentials or whatever)
}
return response;
}
How to use it :
System.out.println(httpRequest(new URL("https://authserver.mojang.com/authenticate"), MakeJSONRequest("YourUsername", "YourPassword")));
来源:https://stackoverflow.com/questions/23457364/java-minecraft-authentication