Commit c1a40b5e by Patryk Czarnik

Klienty HTTP zawarte w Java SE

parent 1c61ea56
...@@ -6,3 +6,5 @@ ...@@ -6,3 +6,5 @@
/*.iml /*.iml
/.idea/ /.idea/
/wynik*
package sklep.klient_rest;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
public class P01_Url {
public static void main(String[] args) {
try {
URL url = new URL("http://localhost:8080/PC33-RestSerwer/products.json");
try(InputStream inputStream = url.openStream()) {
Files.copy(inputStream, Paths.get("wynik01.json"), StandardCopyOption.REPLACE_EXISTING);
System.out.println("OK");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
package sklep.klient_rest;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
public class P03_HttpClient {
public static void main(String[] args) {
HttpClient httpClient = HttpClient.newHttpClient();
try {
URI uri = new URI("http://localhost:8080/PC33-RestSerwer/products.json");
HttpRequest request = HttpRequest.newBuilder(uri).build();
HttpResponse<String> response = httpClient.send(request, BodyHandlers.ofString());
System.out.println("response " + response);
System.out.println("status: " + response.statusCode());
System.out.println("Content-Type: " + response.headers().firstValue("Content-Type").orElse("BRAK"));
String body = response.body();
System.out.println("Rozmiar treści: " + body.length());
System.out.println("\nCała treść:\n");
System.out.println(body);
} catch (URISyntaxException | IOException | InterruptedException 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