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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Bump.sh

Hate writing docs?

Hate undocumented APIs even more?

Bump.sh generates an always up-to-date API reference site for REST and Event-Driven Architectures.

Plug it in your CI. It fetches your OpenAPI and AsyncAPI (GraphQL pending) spec files, and even generates a diff. Gather all of your API docs in a single source of truth.

Try it for free

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay