AppPackage.Session.java Source code

Java tutorial

Introduction

Here is the source code for AppPackage.Session.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package AppPackage;

import static AppPackage.MainGUI.startDir;
import static AppPackage.MainGUI.fileUtil;
import static AppPackage.MainGUI.debug;
import java.io.*;
import java.math.BigInteger;
import org.json.simple.*;
import java.net.*;
import java.security.SecureRandom;

/**
 *
 * @author Dominik
 */
public class Session {

    private SecureRandom random = new SecureRandom();

    public String generateToken() {
        return new BigInteger(130, random).toString(32);
    }

public String doLogin(String username, String password) {
    String returnVal = "";
        
    try {

    URL url = new URL("https://authserver.mojang.com/authenticate");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/json");

    String token = this.generateToken();`
        
    String input = "{\"agent\": {\"name\": \"Minecraft\",\"version\": 99},\"username\": \""+username+"\",\"password\": \""+password+"\",\"clientToken\": \""+token+"\"}";

    OutputStream os = conn.getOutputStream();
    os.write(input.getBytes());
    os.flush();

    if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
        debug.message("Failed : HTTP error code : " + conn.getResponseCode());
    }

    BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

    String output = br.readLine();
    debug.message("Output from Server ....");
    if (output != null) {
        debug.message(output);
        returnVal = "true";
    }
    else {
        debug.error("Auth server is not responding.");
    }

    conn.disconnect();

    } catch (Exception e) {

        debug.error("Error while contacting auth server.");
        debug.message(e.toString());
        returnVal = "false";

    }
    return returnVal;
}
}