Commit 93582b02 by Patryk Czarnik

Klient REST oparty o RestEasy, ale bez klas modelu

parent 23ca5000
...@@ -9,6 +9,7 @@ ...@@ -9,6 +9,7 @@
<properties> <properties>
<maven.compiler.release>17</maven.compiler.release> <maven.compiler.release>17</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<resteasy.version>6.2.4.Final</resteasy.version>
</properties> </properties>
<build> <build>
...@@ -36,5 +37,20 @@ ...@@ -36,5 +37,20 @@
<artifactId>parsson</artifactId> <artifactId>parsson</artifactId>
<version>1.1.4</version> <version>1.1.4</version>
</dependency> </dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-client</artifactId>
<version>${resteasy.version}</version>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jaxb-provider</artifactId>
<version>${resteasy.version}</version>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jackson2-provider</artifactId>
<version>${resteasy.version}</version>
</dependency>
</dependencies> </dependencies>
</project> </project>
\ No newline at end of file
package sklep.klient;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import jakarta.ws.rs.client.Client;
import jakarta.ws.rs.client.ClientBuilder;
import jakarta.ws.rs.client.Invocation;
import jakarta.ws.rs.client.WebTarget;
import jakarta.ws.rs.core.Response;
// Ten i kolejne przykłady pokazują jak aplikacja kliencka napisana w Javie może wysyłać
// zapytania do usługi REST-owej (głównie GET, jest też gdzieś POST)
// korzystając z technologii JAX-RS "po stronie klienta".
// Aby z tego skorzystać, do projektu trzeba dodać bibliotekę z implementacją JAX-RS.
// Tutaj jest to resteasy-client.
public class Klient11_RestClient {
public static void main(String[] args) {
System.out.println("Startujemy");
Client client = ClientBuilder.newClient();
System.out.println("Przygotowuję zapytanie");
WebTarget target = client.target(Ustawienia.ADRES_USLUGI).path("products.json");
Invocation invocation = target.request().buildGet();
System.out.println("Wysyłam zapytanie");
Response response = invocation.invoke();
// Wynikiem jest obiekt klasy Response - tej samej, co na serwerze (używaliśmy np. do generowania kodów 404).
// W obiekcie można sprawdzić informacji o odpowiedzi: media type, status code.
System.out.println("Mam odpowiedź: " + response);
System.out.println("Status: " + response.getStatus());
System.out.println("C-Type: " + response.getMediaType());
System.out.println("Length: " + response.getLength());
// Aby odczytać zawartość zwróconą przez serwer, używamy metody readEntity.
// (przy domyślnych ustawieniach) tę metodę można wywołać tylko raz.
// Dopiero w tym momencie podajemy typ, na który zostanie skonwertowana treść odpowiedzi
// (w miarę możliwości - po prostu niektóre typy zadziałają, a niektóre nie).
byte[] dane = response.readEntity(byte[].class);
System.out.println("Dane mają " + dane.length + " bajtów.");
try {
Files.write(Paths.get("wynik11.json"), dane);
System.out.println("Zapisałem w pliku");
} catch (IOException e) {
System.err.println(e);
}
System.out.println("Koniec");
}
}
package sklep.klient;
import jakarta.ws.rs.client.Client;
import jakarta.ws.rs.client.ClientBuilder;
import jakarta.ws.rs.core.Response;
public class Klient12_RestClient_String {
public static void main(String[] args) {
Client client = ClientBuilder.newClient();
// Taki styl programowania to "fluent API"
Response response = client.target(Ustawienia.ADRES_USLUGI)
.path("products.json")
.request().buildGet()
.invoke();
System.out.println("Mam odpowiedź: " + response);
System.out.println("Status: " + response.getStatus());
System.out.println("C-Type: " + response.getMediaType());
System.out.println("Length: " + response.getLength());
// readEntity(OKREŚLENIE TYPU) stara się odczytać tresc odpowiedzi jako obiekt podanego typu
// Obsługiwane typy to m.in: byte[], String, InputStream, File
// Dodając odpowiednie "MeassgeBodyReader", możemy obsługiwać dowolne typy.
// W szczególności, gdy dodamy do projektu obsługę XML lub JSON (zob. zależności Mavena),
// będziemy mogli odczytywać dane w postaci obiektów naszego modelu, np. Product.
String dane = response.readEntity(String.class);
System.out.println("Otrzymane dane:");
System.out.println(dane);
}
}
package sklep.klient;
import java.awt.HeadlessException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import javax.swing.JOptionPane;
import jakarta.ws.rs.client.Client;
import jakarta.ws.rs.client.ClientBuilder;
import jakarta.ws.rs.core.Response;
public class Klient13_RestClient_Multiformat {
public static void main(String[] args) {
try {
Client client = ClientBuilder.newClient();
String[] formaty = {"txt", "json", "xml", "pdf"};
String format = (String) JOptionPane.showInputDialog(null, "Wybierz format danych", "Wybór",
JOptionPane.QUESTION_MESSAGE, null, formaty, "txt");
String mediaType = switch(format) {
case "txt" -> "text/plain";
case "json" -> "application/json";
case "xml" -> "application/xml";
case "pdf" -> "application/pdf";
default -> throw new IllegalArgumentException();
};
// Klient może wybrać format (mediaType), w jakim oczekuje odpowiedzi - to wpływa na nagłówek Accept
Response response = client.target(Ustawienia.ADRES_USLUGI)
.path("products")
.request(mediaType)
.buildGet()
.invoke();
JOptionPane.showMessageDialog(null, String.format("""
Status: %d
C-Type: %s
Length: %d""", response.getStatus(), response.getMediaType(), response.getLength()));
Path plik = Paths.get("wynik13." + format);
InputStream stream = response.readEntity(InputStream.class);
Files.copy(stream, plik, StandardCopyOption.REPLACE_EXISTING);
JOptionPane.showMessageDialog(null, "Zapisano plik " + plik);
} catch(Exception e) {
e.printStackTrace();
}
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment