I need to make an API that captures some machine data (OS name, cpu usage, network usage etc.) and send as JSON. I was able to capture the data and make it appear on the console in the form of JSON, however, I never moved with the SEND of data. I gave one a lookup on HTTPRequest, but I did not understand how to use it. Remember, I move with Java only 3 months, so if you can help me understand how I can send this, I thank you immensely!
Personal, this is the code I'm currently in. I'm returning a STRING with Json from the CPUINFO class, but if any application "pulls" it, it will pull in String format, not Json, right? Can I get him to return to Json?
public class ServerHTTP {
static CPUINFO infocpu = new CPUINFO();
public static void main(String[] args) throws IOException {
HttpServer server = HttpServer.create(new InetSocketAddress(9080), 0);
System.out.println("Executando");
server.createContext("/teste", new MyHandler());
server.createContext("/", new HomeHandler());
server.createContext("/dados", new dataHandler());
server.setExecutor(null);
server.start();
}
static class MyHandler implements HttpHandler {
public void handle(HttpExchange t) throws IOException {
Headers h = t.getResponseHeaders();
h.add("Content-Type", "application/json");
String response = "<h1> Hello World! </h1>";
t.sendResponseHeaders(200, response.length());
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
static class HomeHandler implements HttpHandler {
public void handle(HttpExchange t) throws IOException {
Headers h = t.getResponseHeaders();
h.add("Access-Control-Allow-Origin", "*");
h.add("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
String response = "<h> Homepage </h>";
t.sendResponseHeaders(200, response.length());
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
static class dataHandler implements HttpHandler {
public void handle(HttpExchange he) throws IOException {
Headers h = he.getResponseHeaders();
h.add("Access-Control-Allow-Origin", "*");
h.add("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
String response = infocpu + "";
he.sendResponseHeaders(200, response.length());
OutputStream os = he.getResponseBody();
os.write(response.toString().getBytes());
os.close();
}
}