DEV Community

Edgar Rios Navarro
Edgar Rios Navarro

Posted on

2 2

Demo Swing y API REST

Por mucho tiempo, hemos considerado una aplicación de escritorio como Cliente/Servidor; donde el "Servidor" es una base de datos.

Sin embargo, con el creciente uso de servicios; surge la necesidad de conectarnos e interactuar constantemente.

Dependiendo de la necesidad y el caso de uso, podemos emplear:

  • gRPC
  • GraphQL
  • WebSocket
  • API Rest
  • SOAP

El estándar actual es utilizar Rest/JSON.


Desde Java 11 nos provee un nuevo (y mejorado) HTTP Client.

Para agregar nuevos registros, envíamos los datos mediante una petición POST.

BookDto newBook = new BookDto("New book from Swing", 250);
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("http://localhost:8080/books"))
.headers("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(mapper.writeValueAsString(newBook)) )
.build();
view raw FacadeAdd.java hosted with ❤ by GitHub

201
{"id":1,"title":"New book from Swing","pages":250}
201
{"id":2,"title":"New book from Swing","pages":250}
201
{"id":3,"title":"New book from Swing","pages":250}
Enter fullscreen mode Exit fullscreen mode

Recuperamos el listado, al invocar el método GET y lo mostramos en la grilla.

HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("http://localhost:8080/books"))
.GET()
.build();
...
dataModel.deleteRows();
List<BookDto> books = mapper.readValue(response.body(), new TypeReference<>(){});
books.forEach(
b -> {
Object[] row = {
String.valueOf(b.getId()),
b.getTitle(),
b.getPages()
};
dataModel.insertRow(row);
}
);

Image description


Documentación

https://www.baeldung.com/java-9-http-client
SwingApp-Front

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

Top comments (0)