Como criar e consumir uma API REST simples em Java puro

Vou criar uma API REST simples em Java puro** (usando com.sun.net.httpserver) e consumir essa API usando java.net.HttpURLConnection. Parte 1: Criando a API (Servidor HTTP) Passo 1: Estrutura do Projeto src └── main └── java ├── api │ ├── Task.java // Modelo de dados │ ├── TaskHandler.java // Manipulador de requisições │ └── Server.java // Servidor principal └── client └── ApiClient.java // Cliente para consumir a API Passo 2: Código do Servidor Classe Task (Modelo) package api; public class Task { private int id; private String title; private boolean completed; // Construtor, getters e setters public Task(int id, String title, boolean completed) { this.id = id; this.title = title; this.completed = completed; } public int getId() { return id; } public String getTitle() { return title; } public boolean isCompleted() { return completed; } } Classe TaskHandler (Manipulador de Requisições) package api; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; public class TaskHandler implements HttpHandler { private List tasks = new ArrayList(); private int nextId = 1; @Override public void handle(HttpExchange exchange) throws IOException { String method = exchange.getRequestMethod(); String path = exchange.getRequestURI().getPath(); switch (method) { case "GET": handleGet(exchange); break; case "POST": handlePost(exchange); break; default: sendResponse(exchange, 405, "{\"error\": \"Método não permitido\"}"); } } private void handleGet(HttpExchange exchange) throws IOException { String json = "["; for (Task task : tasks) { json += String.format( "{\"id\": %d, \"title\": \"%s\", \"completed\": %b},", task.getId(), task.getTitle(), task.isCompleted() ); } json = json.isEmpty() ? "[]" : json.substring(0, json.length() - 1) + "]"; sendResponse(exchange, 200, json); } private void handlePost(HttpExchange exchange) throws IOException { String body = new String(exchange.getRequestBody().readAllBytes()); // Simples parsing (em produção, use uma biblioteca JSON) String title = body.split("\"")[3]; // Extrai o título do JSON Task task = new Task(nextId++, title, false); tasks.add(task); sendResponse(exchange, 201, "{\"id\": " + task.getId() + "}"); } private void sendResponse(HttpExchange exchange, int statusCode, String response) throws IOException { exchange.getResponseHeaders().set("Content-Type", "application/json"); exchange.sendResponseHeaders(statusCode, response.getBytes().length); try (OutputStream os = exchange.getResponseBody()) { os.write(response.getBytes()); } } } Classe Server (Iniciar Servidor) package api; import com.sun.net.httpserver.HttpServer; import java.io.IOException; import java.net.InetSocketAddress; public class Server { public static void main(String[] args) throws IOException { HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0); server.createContext("/tasks", new TaskHandler()); server.start(); System.out.println("Servidor iniciado na porta 8080"); } } Parte 2: Consumindo a API (Cliente HTTP) Classe ApiClient package client; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; import java.io.OutputStream; import java.io.InputStream; import java.util.Scanner; public class ApiClient { public static String get(String url) throws IOException { HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestMethod("GET"); try (InputStream is = conn.getInputStream(); Scanner scanner = new Scanner(is)) { return scanner.useDelimiter("\\A").next(); } } public static String post(String url, String jsonBody) throws IOException { HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setDoOutput(true); try (OutputStream os = conn.getOutputStream()) { os.write(jsonBody.getBytes()); } try (InputStream is = conn.getInputStream(); Scanner scanner = new Scanner(is)) { return scanner.useDelimiter("\\A").next();

Mar 6, 2025 - 23:57
 0
Como criar e consumir uma API REST simples em Java puro

Vou criar uma API REST simples em Java puro** (usando com.sun.net.httpserver) e consumir essa API usando java.net.HttpURLConnection.

Parte 1: Criando a API (Servidor HTTP)

Passo 1: Estrutura do Projeto

src
└── main
    └── java
        ├── api
        │   ├── Task.java          // Modelo de dados
        │   ├── TaskHandler.java   // Manipulador de requisições
        │   └── Server.java        // Servidor principal
        └── client
            └── ApiClient.java     // Cliente para consumir a API

Passo 2: Código do Servidor

Classe Task (Modelo)
package api;

public class Task {
    private int id;
    private String title;
    private boolean completed;

    // Construtor, getters e setters
    public Task(int id, String title, boolean completed) {
        this.id = id;
        this.title = title;
        this.completed = completed;
    }

    public int getId() { return id; }
    public String getTitle() { return title; }
    public boolean isCompleted() { return completed; }
}
Classe TaskHandler (Manipulador de Requisições)
package api;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

public class TaskHandler implements HttpHandler {
    private List<Task> tasks = new ArrayList<>();
    private int nextId = 1;

    @Override
    public void handle(HttpExchange exchange) throws IOException {
        String method = exchange.getRequestMethod();
        String path = exchange.getRequestURI().getPath();

        switch (method) {
            case "GET":
                handleGet(exchange);
                break;
            case "POST":
                handlePost(exchange);
                break;
            default:
                sendResponse(exchange, 405, "{\"error\": \"Método não permitido\"}");
        }
    }

    private void handleGet(HttpExchange exchange) throws IOException {
        String json = "[";
        for (Task task : tasks) {
            json += String.format(
                "{\"id\": %d, \"title\": \"%s\", \"completed\": %b},",
                task.getId(), task.getTitle(), task.isCompleted()
            );
        }
        json = json.isEmpty() ? "[]" : json.substring(0, json.length() - 1) + "]";
        sendResponse(exchange, 200, json);
    }

    private void handlePost(HttpExchange exchange) throws IOException {
        String body = new String(exchange.getRequestBody().readAllBytes());
        // Simples parsing (em produção, use uma biblioteca JSON)
        String title = body.split("\"")[3]; // Extrai o título do JSON
        Task task = new Task(nextId++, title, false);
        tasks.add(task);
        sendResponse(exchange, 201, "{\"id\": " + task.getId() + "}");
    }

    private void sendResponse(HttpExchange exchange, int statusCode, String response) throws IOException {
        exchange.getResponseHeaders().set("Content-Type", "application/json");
        exchange.sendResponseHeaders(statusCode, response.getBytes().length);
        try (OutputStream os = exchange.getResponseBody()) {
            os.write(response.getBytes());
        }
    }
}
Classe Server (Iniciar Servidor)
package api;

import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.net.InetSocketAddress;

public class Server {
    public static void main(String[] args) throws IOException {
        HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
        server.createContext("/tasks", new TaskHandler());
        server.start();
        System.out.println("Servidor iniciado na porta 8080");
    }
}

Parte 2: Consumindo a API (Cliente HTTP)

Classe ApiClient

package client;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.OutputStream;
import java.io.InputStream;
import java.util.Scanner;

public class ApiClient {

    public static String get(String url) throws IOException {
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        conn.setRequestMethod("GET");

        try (InputStream is = conn.getInputStream();
             Scanner scanner = new Scanner(is)) {
            return scanner.useDelimiter("\\A").next();
        }
    }

    public static String post(String url, String jsonBody) throws IOException {
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setDoOutput(true);

        try (OutputStream os = conn.getOutputStream()) {
            os.write(jsonBody.getBytes());
        }

        try (InputStream is = conn.getInputStream();
             Scanner scanner = new Scanner(is)) {
            return scanner.useDelimiter("\\A").next();
        }
    }

    public static void main(String[] args) {
        try {
            // POST: Criar uma tarefa
            String responsePost = post("http://localhost:8080/tasks", 
                "{\"title\": \"Aprender Java\", \"completed\": false}");
            System.out.println("POST Response: " + responsePost);

            // GET: Listar tarefas
            String responseGet = get("http://localhost:8080/tasks");
            System.out.println("GET Response: " + responseGet);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Passo 3: Execução

  1. Inicie o Servidor:
   java api.Server
  1. Execute o Cliente:
   java client.ApiClient

Testando com cURL (Opcional)

# Criar tarefa
curl -X POST -H "Content-Type: application/json" -d "{\"title\":\"Estudar API\",\"completed\":false}" http://localhost:8080/tasks

# Listar tarefas
curl http://localhost:8080/tasks

Considerações

  1. Simplicidade vs. Robustez:

    • O servidor usa com.sun.net.httpserver, ideal para protótipos. Em produção, prefira frameworks como Spring Boot ou Javalin.
    • O parsing de JSON é simplificado. Use bibliotecas como Jackson ou Gson para manipulação real de JSON.
  2. Cliente HTTP:

    • Para projetos reais, use HttpClient (Java 11+) ou bibliotecas como OkHttp.
  3. Melhorias Possíveis:

    • Adicionar tratamento de erros.
    • Implementar métodos PUT e DELETE.
    • Validar entradas.