Solved How to listen for HTTP requests in minecraft

Discussion in 'Spigot Plugin Development' started by Super02, Jun 15, 2018.

  1. Hello, I'm making a project with a friend where we are trying to do something where you can make a post request and he gave me this code and asked me if I can do so when it gets a post request it will broadcast in chat what the data was
    Code (Java):
    package commands;
    import java.io.IOException;
    import java.io.OutputStream;
    import java.net.InetSocketAddress;

    import com.sun.net.httpserver.HttpExchange;
    import com.sun.net.httpserver.HttpHandler;
    import com.sun.net.httpserver.HttpServer;

    public class GetRequest {
       
        public static void main(String[] args) throws Exception {
            System.out.print("Starting server...");
            HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
            server.createContext("/", new MyHandler());
            server.setExecutor(null); // creates a default executor
            server.start();
            System.out.print("Server started succesfuly");
        }



        static class MyHandler implements HttpHandler {
            @Override
            public void handle(HttpExchange t) throws IOException {
               
                String response = t.getRequestURI().getQuery() + " ";
                if(t.getRequestURI().getQuery() != null) {
                System.out.print(response);
                }
                t.sendResponseHeaders(200, response.length());
                OutputStream os = t.getResponseBody();
                os.write(response.getBytes());
                os.close();
            }
        }
        }
     
  2. Your question is a basic Java 101 question regarding how to handle classes and objects. You don't know how to get this object in your main class of the plugin to do it's thing.

    Take a step back and learn the basics. It might sound mean, and hurtful, but you'll thank me later if you do it.
     
    • Informative Informative x 1
  3. Ok I'll try that :) but thanks for the help anyway :)