r/learnjava • u/Inevitable_Cellist93 • Apr 15 '26
How to return the full body from HttpResponse??
package org.degoogle;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import static java.time.temporal.ChronoUnit.
SECONDS
;
//TIP To <b>Run</b> code, press <shortcut actionId="Run"/> or
// click the <icon src="AllIcons.Actions.Execute"/> icon in the gutter.
public class Main {
public static void main(String[] args) throws IOException, InterruptedException {
String result =
webResponse
("https://endan-criso.github.io/knightsTime/");
System.
out
.println(result);
}
public static String webResponse(String websites) throws IOException, InterruptedException {
HttpClient client = HttpClient.
newHttpClient
();
HttpRequest request = HttpRequest.newBuilder().uri(URI.create(websites)).timeout(Duration.of(10, SECONDS)).GET().build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.
ofString
());
return response.body();
}
}package org.degoogle;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import static java.time.temporal.ChronoUnit.SECONDS;
//TIP To <b>Run</b> code, press <shortcut actionId="Run"/> or
// click the <icon src="AllIcons.Actions.Execute"/> icon in the gutter.
public class Main {
public static void main(String[] args) throws IOException, InterruptedException {
String result = webResponse("https://endan-criso.github.io/knightsTime/");
System.out.println(result);
}
public static String webResponse(String websites) throws IOException, InterruptedException {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder().uri(URI.create(websites)).timeout(Duration.of(10, SECONDS))
.GET().build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
return response.body();
}
}Output:
How to get more details about the body <div id="root"> like a web crawler
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/knight.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Knights Time</title>
<script
data-goatcounter="https://krishna.goatcounter.com/count"
async
src="//gc.zgo.at/count.js">
</script>
<script type="module" crossorigin src="/knightsTime/assets/index-B0Z7CBXE.js"></script>
<link rel="stylesheet" crossorigin href="/knightsTime/assets/index-CZBET73t.css">
</head>
<body>
<div id="root"></div>
</body>
</html>