Solved Web API giving 400 Bad Request Message

Discussion in 'Plugin Development' started by CommonSenze, Aug 14, 2017.

Thread Status:
Not open for further replies.
  1. Offline

    CommonSenze

    SOLVED - After a long diagnose and look through I got to fix the problem.

    ----------------------------------------------------------------------------------------------

    Hello and welcome fellow coders I have an intense problem I can't seem to shake on my own.

    I am currently coding a Web API for my server and want the server to send the players trimmed UUID and the type of action I want it to go to to handle the UUID.

    The problem with my code is during connection I get a 400 Bad Request page when I print my data on my "PlayerLoginEvent":

    Code:java
    1.  
    2. package me.commonsenze.banmanager;
    3.  
    4. import com.eclipsesource.json.JsonObject;
    5. import com.evilmidget38.UUIDFetcher;
    6. import org.bukkit.Bukkit;
    7. import org.bukkit.ChatColor;
    8. import org.bukkit.command.Command;
    9. import org.bukkit.command.CommandSender;
    10. import org.bukkit.entity.Player;
    11. import org.bukkit.event.EventHandler;
    12. import org.bukkit.event.Listener;
    13. import org.bukkit.event.player.PlayerLoginEvent;
    14. import org.bukkit.plugin.java.JavaPlugin;
    15.  
    16. import java.io.BufferedReader;
    17. import java.io.DataOutputStream;
    18. import java.io.FileNotFoundException;
    19. import java.io.InputStreamReader;
    20. import java.net.HttpURLConnection;
    21. import java.net.URL;
    22. import java.nio.charset.Charset;
    23. import java.util.Arrays;
    24. import java.util.UUID;
    25.  
    26.  
    27. public class BanManager extends JavaPlugin implements Listener {
    28.  
    29. @Override
    30. public void onEnable(){
    31.  
    32. Bukkit.getServer().getPluginManager().registerEvents(this, this);
    33. }
    34.  
    35. @SuppressWarnings("deprecation")
    36. public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args){
    37. if (sender.hasPermission("commonbans."+commandLabel)){
    38. if (args.length == 0){
    39. sender.sendMessage(""+ ChatColor.RED +ChatColor.BOLD + "!-" +ChatColor.GRAY + "/"+commandLabel+" <player> [reason]");
    40. return true;
    41. }
    42. } else {
    43. sender.sendMessage(ChatColor.GRAY+ "Unknown command. Type '" + ChatColor.GREEN + "/help" +ChatColor.GRAY + "' for help");
    44. return true;
    45. }
    46. String name;
    47. UUID uuid;
    48. if (isUUID(args[0])){
    49. uuid = UUID.fromString(args[0]);
    50. name = Bukkit.getOfflinePlayer(uuid).getName();
    51. } else {
    52. name = args[0];
    53. try {
    54. // Get UUID from a name
    55. uuid = new UUIDFetcher(Arrays.asList(name)).call().get(name);
    56. } catch (Exception e) {
    57. e.printStackTrace();
    58. return true;
    59. }
    60. }
    61. if (cmd.getName().equalsIgnoreCase("ban")){
    62. try {
    63. StringBuilder message = new StringBuilder();
    64. for (int i = 1; i < args.length; i++){
    65. message.append(args).append(" ");
    66. }
    67. String msg = ChatColor.stripColor(message.toString().trim());
    68. if (msg.isEmpty()){
    69. msg = "No reason specified";
    70. }
    71. // "add" is my API php name that adds the player to a banned mySQL database
    72. HttpURLConnection connection = connect("add", "uuid=" + uuid.toString().replaceAll("-", "") + "&reason=" + msg.replaceAll(" ", "%20"));
    73. BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    74. String data = in.readLine();
    75.  
    76. if (data == null || data.equals("key")) {
    77. sender.sendMessage(ChatColor.RED + "BanManagement's config file is not configured properly.");
    78. } else {
    79. sender.sendMessage(ChatColor.GREEN + "You banned "+name);
    80. Player t = Bukkit.getPlayer(name);
    81. if (t != null){
    82. if (msg.isEmpty()){
    83. t.kickPlayer(""+ChatColor.GRAY + ChatColor.RED + "Permanently Banned"+"\n"+ChatColor.GRAY+"You may buy an unban pass at "+ChatColor.WHITE+"[URL]https://simplicpvp.buycraft.net/[/URL]");
    84. } else {
    85. t.kickPlayer(""+ChatColor.GRAY + ChatColor.RED + "Permanently Banned\n"+ChatColor.GRAY +"Reason:"+ChatColor.YELLOW+" "+msg+"\n"+ChatColor.GRAY+"You may buy an unban pass at "+ChatColor.WHITE+"[URL]https://simplicpvp.buycraft.net/[/URL]");
    86. }
    87. }
    88. if (args[1].equalsIgnoreCase("-s")){
    89. Bukkit.getServer().broadcastMessage(ChatColor.GREEN+ name + " has been banned");
    90. } else {
    91. Bukkit.getServer().broadcastMessage(ChatColor.GREEN+ name + " was been banned by " + sender.getName());
    92. }
    93. }
    94. }
    95.  
    96. sender.sendMessage(ChatColor.RED + "BanManagement's config file is not configured properly.");
    97. return true;
    98. }
    99.  
    100. catch (Exception e) {
    101. e.printStackTrace();
    102. }
    103. }
    104. if (cmd.getName().equalsIgnoreCase("unban")){
    105. try {
    106. // "add" is my API php name that removes the player to a banned mySQL database
    107. HttpURLConnection connection = connect("remove", "uuid=" + uuid.toString().replaceAll("-", ""));
    108. BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    109. String data = in.readLine();
    110.  
    111. if (data == null || data.equals("key")) {
    112. sender.sendMessage(ChatColor.RED + "BanManagement's config file is not configured properly.");
    113. } else {
    114. sender.sendMessage(ChatColor.GREEN + "You unbanned "+name);
    115. Bukkit.getServer().broadcastMessage(ChatColor.GREEN+ name + " was been unbanned " +sender.getName());
    116. }
    117. }
    118.  
    119. sender.sendMessage(ChatColor.RED + "BanManagement's config file is not configured properly.");
    120. return true;
    121. }
    122.  
    123. catch (Exception e) {
    124. e.printStackTrace();
    125. }
    126. }
    127. if (cmd.getName().equalsIgnoreCase("checkban")){
    128. try {
    129. // "add" is my API php name that gets the player to a banned mySQL database
    130. HttpURLConnection connection = connect("get", "uuid=" + uuid.toString().replaceAll("-", ""));
    131. BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    132. String data = in.readLine();
    133.  
    134. if (data == null || data.equals("key")) {
    135. sender.sendMessage(ChatColor.RED + "BanManagement's config file is not configured properly.");
    136. } else {
    137. if (data.equals("[]")) {
    138. sender.sendMessage(ChatColor.RED + "No ban found.");
    139. }
    140.  
    141. else {
    142. JsonObject jsonObject = JsonObject.readFrom(data);
    143.  
    144. sender.sendMessage(ChatColor.GREEN + "Ban ID: " + jsonObject.getString("id", "null"));
    145. sender.sendMessage(ChatColor.GREEN + "UUID: " + jsonObject.getString("uuid", "null"));
    146. sender.sendMessage(ChatColor.GREEN + "Date: " + jsonObject.getString("date", "null"));
    147. sender.sendMessage(ChatColor.GREEN + "Reason: " + jsonObject.getString("reason", "null"));
    148. }
    149. }
    150. }
    151.  
    152. sender.sendMessage(ChatColor.RED + "BanManagement's config file is not configured properly.");
    153. return true;
    154. }
    155.  
    156. catch (Exception e) {
    157. e.printStackTrace();
    158. }
    159. }
    160. return true;
    161. }
    162.  
    163. @SuppressWarnings("deprecation")
    164. @EventHandler
    165. public void onPlayerLogin(PlayerLoginEvent e) {
    166. try {
    167. HttpURLConnection connection = connect("get", "uuid=" + e.getPlayer().getUniqueId().toString().replaceAll("-",""));
    168. BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    169. String data = in.readLine();
    170.  
    171. if (data == null || data.equals("key")) {
    172. e.disallow(PlayerLoginEvent.Result.KICK_BANNED, ChatColor.RED + "BanManagement's config file is not configured properly.");
    173. }
    174.  
    175. else if (!data.equals("[]")) {
    176. // My debug
    177. System.out.println("-------");
    178. System.out.println(data);
    179. System.out.println("-------");
    180. System.out.println(e.getPlayer().getUniqueId().toString().replaceAll("-",""));
    181. System.out.println("-------");
    182. // JsonObject jsonObject = JsonObject.readFrom(data);
    183. // System.out.println(data);
    184. // System.out.println("------------");
    185. // System.out.println("Simplified");
    186. // System.out.println("Ban ID: " + jsonObject.getString("id", "null"));
    187. // System.out.println("UUID: " + jsonObject.getString("uuid", "null"));
    188. // System.out.println("Date: " + jsonObject.getString("date", "null"));
    189. // System.out.println("Reason: " + jsonObject.getString("reason", "null"));
    190. }
    191. else {
    192. System.out.println("not banned");
    193. }
    194. }
    195.  
    196. catch (FileNotFoundException ex) {
    197. e.disallow(PlayerLoginEvent.Result.KICK_BANNED, ChatColor.RED + "BanManagement's config file is not configured properly.");
    198. }
    199.  
    200. catch (Exception ex) {
    201. ex.printStackTrace();
    202. }
    203. }
    204.  
    205. private HttpURLConnection connect(String api, String args){
    206. try {
    207. args = "key=*******&"+args;
    208. byte[] data = args.getBytes(Charset.forName("UTF-8"));
    209. int length = args.length();
    210. String request = "[URL]http://www.simplic.epizy.com/API/[/URL]"+api+".php?"+args;
    211. // Problem in this line^
    212. URL url = new URL(request);
    213. HttpURLConnection connect = (HttpURLConnection) url.openConnection();
    214. connect.setDoInput(true);
    215. connect.setDoOutput(true);
    216. connect.setRequestMethod("POST");
    217. connect.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    218. connect.setRequestProperty("charset", "UTF-8");
    219. connect.setRequestProperty("Content-Length", String.valueOf(length));
    220.  
    221. DataOutputStream out = new DataOutputStream(connect.getOutputStream());
    222. out.write(data);
    223. out.flush();
    224. out.close();
    225. return connect;
    226. } catch (Exception e) {
    227. e.printStackTrace();
    228. return null;
    229. }
    230. }
    231.  
    232. public boolean isUUID(String s){
    233. if (s.matches("[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}")){
    234. return true;
    235. } else {
    236. return false;
    237. }
    238. }
    239. }
    240.  


    Here's my PHP code.
    The API main file:
    PHP:
    <?php
        define
    ("key"file_get_contents('*******'));
        function 
    get_bans(){
            
    $servername "*******";
            
    $username "******";
            
    $password "*****";
            
    $database "********";

            
    // Create connection
            
    $con = new mysqli($servername$username$password$database);
            if (
    $con->connect_error){
                die(
    $con->connect_error);
            }
            return 
    $con;
        }

        function 
    add($name$reason$banner){
            
    $url "https://api.mojang.com/users/profiles/minecraft/" $name;
            
    $content file_get_contents($url);
            
    $json json_decode($content);
            
    $uuid $json->id;
            
    $date date("Y-m-d H:i:s");
            
    get_bans()->query("insert into bans (name, uuid, date, reason, banner) VALUES ('$name','$uuid','$date','$reason','$banner')");
        }

        function 
    remove($uuid){
            
    get_bans()->query("delete from bans where uuid='$uuid'");
        }

        function 
    remove_id($id) {
            
    get_mysql()->query("delete from bans where id = $id");
        }

        function 
    get($uuid){
            return 
    get_bans()->query("select * from bans where uuid='$uuid'")->fetch_assoc();
        }

        function 
    get_id($id){
            return 
    get_bans()->query("select * from bans where id='$id'")->fetch_assoc();
        }

        function 
    get_all_bans(){
            return 
    get_bans()->query("select * from bans");
        }
    The Get file:
    PHP:
    <?php
    require 'api.php';
    session_start();
    $auth false;
            if (isset(
    $_POST['key']) && $_POST['key'] == key){
                
    $auth true;
            }
    if (!empty(
    $_SESSION['name']) && $_SESSION['name'] == 'CommonSenze'){
        
    $auth true;
    }
    if (!
    $auth){
        echo(
    "key");
        return;
    }
    $data get($_POST["uuid"]);
    echo(
    json_encode($data != null $data : array()));
    My other files such as add and remove are similar to the Get file so I wont add them in.

    Heres what I get back when I print it in console the data I recieve from the server:
    Console Message (open)
    [09:49:29 INFO]: UUID of player _Universal is 4abe3926-1a53-4073-af0a-de59a7b5aedb
    [09:49:30 INFO]: -------
    [09:49:30 INFO]: <html><body><script type="text/javascript" src="/aes.js" ></script><script>function toNumbers(d){var e=[];d.replace(/(..)/g,function(d){e.push(parseInt(d,16))});return e}function toHex(){for(var d=[],d=1==arguments.length&&arguments[0].constructor==Array?arguments[0]:arguments,e="",f=0;f<d.length;f++)e+=(16>d[f]?"0":"")+d[f].toString(16);return e.toLowerCase()}var a=toNumbers("f655ba9d09a112d4968c63579db590b4"),b=toNumbers("98344c2eee86c3994890592585b49f80"),c=toNumbers("300a1dfce888279f2b5483e897d96b4f");document.cookie="__test="+toHex(slowAES.decrypt(c,2,a,b))+"; expires=Thu, 31-Dec-37 23:55:55 GMT; path=/"; location.href="http://www.simplic.epizy.com/API/get.php?key=******&uuid=4abe39261a534073af0ade59a7b5aedb&i=1";</script><noscript>This site requires Javascript to work, please enable Javascript in your browser or use a browser with Javascript support</noscript></body></html>HTTP/1.1 400 Bad Request
    [09:49:30 INFO]: -------
    [09:49:30 INFO]: 4abe39261a534073af0ade59a7b5aedb
    [09:49:30 INFO]: -------
    [09:49:30 INFO]: _Universal connected


    I tried pretty much everything when it comes to obvious choices, I checked the heck out of google, I looked on Stack Overflow to see if anyone had similar problems, I checked Bukkit Forums (I didn't expect anything I just did.), I even quadruple checked my code but I couldn't see anything wrong with it.

    I apologize if this isn't the place to go for this type of problem. (I'm new to Bukkit Forums... well forums in general)
     
    Last edited: Aug 17, 2017
  2. @CommonSenze
    Wouldn't it be easier to connect to the SQL database directly through Java? Having to pass through PHP all the time just seems like a hassle.
     
  3. Offline

    CommonSenze

    @AlvinB
    You're right. I never knew about that. I was following a video and just saw what he did. I never knew you can connect directly.

    Do you happen to know how to connect directly to a MySQL Database?
     
  4. @CommonSenze
    I'm no expert, but you should be able to use the MySQL driver that's shaded into bukkit. Something like this:
    Code:java
    1. try {
    2. // This initializes the jdbc Driver and makes it do all its magic to register itself.
    3. Class.forName("com.mysql.jdbc.Driver");
    4. Connection connection = DriverManager.getConnection("jdbc:mysql://<address of your MySQL database>", "MyUsername", "MyPassword");
    5. e.printStackTrace();
    6. }
     
  5. Offline

    CommonSenze

    @AlvinB

    Alright I'm trying it now.

    @AlvinB

    It doesn't seem to be working. Every time I load my plugin, the server freezes and crashes.

    My Code:

    Code:java
    1. package me.commonsenze.banmanager;
    2.  
    3. import com.evilmidget38.UUIDFetcher;
    4. import org.bukkit.Bukkit;
    5. import org.bukkit.ChatColor;
    6. import org.bukkit.command.Command;
    7. import org.bukkit.command.CommandSender;
    8. import org.bukkit.entity.Player;
    9. import org.bukkit.event.EventHandler;
    10. import org.bukkit.event.Listener;
    11. import org.bukkit.event.player.PlayerLoginEvent;
    12. import org.bukkit.plugin.java.JavaPlugin;
    13.  
    14. import java.sql.*;
    15. import java.text.DateFormat;
    16. import java.text.SimpleDateFormat;
    17. import java.util.Arrays;
    18. import java.util.Date;
    19. import java.util.UUID;
    20.  
    21.  
    22. public class BanManager extends JavaPlugin implements Listener {
    23.  
    24. Connection c = null;
    25.  
    26. @Override
    27. public void onEnable(){
    28. try {
    29. // This initializes the jdbc Driver and makes it do all its magic to register itself.
    30. Class.forName("com.mysql.jdbc.Driver");
    31. c = DriverManager.getConnection("jdbc:mysql://*******/******", "******", "*****");
    32. e.printStackTrace();
    33. }
    34. Bukkit.getServer().getPluginManager().registerEvents(this, this);
    35. }
    36.  
    37. @SuppressWarnings("deprecation")
    38. public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args){
    39. if (sender.hasPermission("commonbans."+commandLabel)){
    40. if (args.length == 0){
    41. sender.sendMessage(""+ ChatColor.RED +ChatColor.BOLD + "!-" +ChatColor.GRAY + "/"+commandLabel+" <player> [reason]");
    42. return true;
    43. }
    44. } else {
    45. sender.sendMessage(ChatColor.GRAY+ "Unknown command. Type '" + ChatColor.GREEN + "/help" +ChatColor.GRAY + "' for help");
    46. return true;
    47. }
    48. String name;
    49. UUID uuid;
    50. if (isUUID(args[0])){
    51. uuid = UUID.fromString(args[0]);
    52. name = Bukkit.getOfflinePlayer(uuid).getName();
    53. } else {
    54. name = args[0];
    55. try {
    56. uuid = new UUIDFetcher(Arrays.asList(name)).call().get(name);
    57. } catch (Exception e) {
    58. e.printStackTrace();
    59. return true;
    60. }
    61. }
    62. if (cmd.getName().equalsIgnoreCase("ban")) try {
    63. StringBuilder message = new StringBuilder();
    64. for (int i = 1; i < args.length; i++) {
    65. message.append(args).append(" ");
    66. }
    67. String msg = ChatColor.stripColor(message.toString().trim());
    68. if (msg.isEmpty()) {
    69. msg = "No reason specified";
    70. }
    71. Statement statement = c.createStatement();
    72.  
    73. ResultSet res = statement.executeQuery("SELECT * FROM bans WHERE name = '" + name + "'&uuid='" + uuid.toString().replaceAll("-", "") + "';");
    74.  
    75. if (res.next()) {
    76. sender.sendMessage(ChatColor.RED + name + " is already banned");
    77. } else {
    78. DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    79. Date date = new Date();
    80. ResultSet result = statement.executeQuery("INSERT INTO bans ('name', 'uuid', 'date', 'reason', 'banner') "
    81. + "VALUES ('" + name + "','" + uuid.toString().replaceAll("-","") + "','" + dateFormat.format(date)
    82. + "','" + msg + "','" + sender.getName() + "')");
    83. sender.sendMessage(ChatColor.GREEN + "You banned " + name);
    84. Player t = Bukkit.getPlayer(name);
    85. if (t != null) {
    86. if (msg.isEmpty()) {
    87. t.kickPlayer("" + ChatColor.GRAY + ChatColor.RED + "Permanently Banned" + "\n" + ChatColor.GRAY + "You may buy an unban pass at " + ChatColor.WHITE + "[URL]https://simplicpvp.buycraft.net/[/URL]");
    88. } else {
    89. t.kickPlayer("" + ChatColor.GRAY + ChatColor.RED + "Permanently Banned\n" + ChatColor.GRAY + "Reason:" + ChatColor.YELLOW + " " + msg + "\n" + ChatColor.GRAY + "You may buy an unban pass at " + ChatColor.WHITE + "[URL]https://simplicpvp.buycraft.net/[/URL]");
    90. }
    91. }
    92. if (args[1].equalsIgnoreCase("-s")) {
    93. Bukkit.getServer().broadcastMessage(ChatColor.GREEN + name + " has been banned");
    94. } else {
    95. Bukkit.getServer().broadcastMessage(ChatColor.GREEN + name + " was been banned by " + sender.getName());
    96. }
    97. }
    98. } catch (Exception e) {
    99. e.printStackTrace();
    100. }
    101. if (cmd.getName().equalsIgnoreCase("unban")){
    102. try {
    103. Statement statement = c.createStatement();
    104. ResultSet res = statement.executeQuery("SELECT * FROM bans WHERE name = '" + name + "'&uuid='" + uuid.toString().replaceAll("-", "") + "';");
    105.  
    106. if (!res.next()) {
    107. sender.sendMessage(ChatColor.RED + name + " is not banned");
    108. } else {
    109. ResultSet result = statement.executeQuery("DELETE FROM bans WHERE uuid='"+uuid.toString().replaceAll("-","';"));
    110. sender.sendMessage(ChatColor.GREEN + "You unbanned "+name);
    111. Bukkit.getServer().broadcastMessage(ChatColor.GREEN+ name + " was been unbanned " +sender.getName());
    112. }
    113. } catch (Exception e) {
    114. e.printStackTrace();
    115. }
    116. }
    117. if (cmd.getName().equalsIgnoreCase("checkban")){
    118. try {
    119. Statement statement = c.createStatement();
    120. ResultSet res = statement.executeQuery("SELECT * FROM bans WHERE name = '" + name + "'&uuid='" + uuid.toString().replaceAll("-", "") + "';");
    121.  
    122. if (!res.next()) {
    123. sender.sendMessage(ChatColor.RED + name + " is not banned");
    124. } else {
    125. sender.sendMessage(ChatColor.GREEN + name + " is banned");
    126. }
    127. } catch (Exception e) {
    128. e.printStackTrace();
    129. }
    130. }
    131. return true;
    132. }
    133.  
    134. @SuppressWarnings("deprecation")
    135. @EventHandler
    136. public void onPlayerLogin(PlayerLoginEvent e) {
    137. try {
    138. Statement statement = c.createStatement();
    139. String name = e.getPlayer().getName();
    140. ResultSet res = statement.executeQuery("SELECT * FROM bans WHERE name = '" + name + "'&uuid='" + e.getPlayer().getUniqueId().toString().replaceAll("-", "") + "';");
    141. if (!res.next()) {
    142. System.out.println(name + " is not banned");
    143. } else {
    144. System.out.println(name + " is banned");
    145. }
    146. } catch (Exception ex) {
    147. ex.printStackTrace();
    148. }
    149. }
    150.  
    151. public boolean isUUID(String s){
    152. if (s.matches("[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}")){
    153. return true;
    154. } else {
    155. return false;
    156. }
    157. }
    158. }
    159.  


    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
    Last edited: Aug 14, 2017
Thread Status:
Not open for further replies.

Share This Page