Java Code Examples for java.net.http.HttpResponse#body()
The following examples show how to use
java.net.http.HttpResponse#body() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Requester.java From burp-javascript-security-extension with GNU General Public License v3.0 | 6 votes |
/** * Make the HTTP request without using the burp callbacks interface */ public void makeRequestWithoutBurp(){ HttpClient client = HttpClient.newBuilder().followRedirects(HttpClient.Redirect.ALWAYS).build(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(urlString)) .build(); try { HttpResponse<String> response = client.send(request, BodyHandlers.ofString()); statusCode = (short) response.statusCode(); responseBody = response.body(); responseBodyBytes = response.body().getBytes(); } catch (Exception ex) { System.err.println("[-] There was an issue getting the JavaScript file at " + urlString); ex.printStackTrace(); responseBody = NO_DATA_RECEIVED; } }
Example 2
Source File: HttpServerTest.java From piranha with BSD 3-Clause "New" or "Revised" License | 6 votes |
/** * Test file. * * @throws Exception when a serious error occurs. */ @Test public void testFile() throws Exception { HttpServer server = createServer(8765); server.start(); try { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder(URI.create("http://localhost:8765/pom.xml")).build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8)); assertEquals(response.statusCode(), 200); String responseText = response.body(); assertTrue(responseText.contains("modelVersion")); } catch (IOException ioe) { throw new RuntimeException(ioe); } finally { server.stop(); } }
Example 3
Source File: OpenIdAuthenticationManager.java From alf.io with GNU General Public License v3.0 | 6 votes |
private Map<String, Object> retrieveAccessToken(String code){ try { HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(buildClaimsRetrieverUrl())) .header("Content-Type", openIdConfiguration().getContentType()) .POST(HttpRequest.BodyPublishers.ofString(buildRetrieveClaimsUrlBody(code))) .build(); HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); if(HttpUtils.callSuccessful(response)) { logger.trace("Access Token successfully retrieved"); return objectMapper.readValue(response.body(), new TypeReference<>() {}); } else { logger.warn("cannot retrieve access token"); throw new IllegalStateException("cannot retrieve access token. Response from server: " +response.body()); } } catch (Exception e) { logger.error("There has been an error retrieving the access token from the idp using the authorization code", e); throw new RuntimeException(e); } }
Example 4
Source File: GitHub.java From jmbe with GNU General Public License v3.0 | 6 votes |
/** * Download the source code for a release to the specified directory * @param release to download * @param directory to store the downloaded zip file * @return path to the download zip file or null */ public static Path downloadReleaseSourceCode(Release release, Path directory) { HttpClient client = HttpClient.newBuilder() .followRedirects(HttpClient.Redirect.ALWAYS) .build(); System.out.println("Downloading: " + release.getDownloadUrl()); HttpRequest request = HttpRequest.newBuilder().uri(URI.create(release.getDownloadUrl())).build(); try { HttpResponse<Path> response = client.send(request, HttpResponse.BodyHandlers.ofFileDownload(directory, StandardOpenOption.CREATE, StandardOpenOption.WRITE)); System.out.println("Download Complete: HTTP Status " + response.statusCode()); return response.body(); } catch(Exception e) { System.out.println("Download Failed: Error downloading source code from GitHub - " + e.getLocalizedMessage()); e.printStackTrace(); } return null; }
Example 5
Source File: SimpleHttpClient.java From alf.io with GNU General Public License v3.0 | 6 votes |
private SimpleHttpClientCachedResponse callRemoteAndSaveResponse(HttpRequest request) throws IOException { HttpResponse<InputStream> response = null; try { response = httpClient.send(request, HttpResponse.BodyHandlers.ofInputStream()); } catch (InterruptedException exception) { Thread.currentThread().interrupt(); logInterruption(exception); } Path tempFile = null; if (HttpUtils.callSuccessful(response)) { InputStream body = response.body(); if (body != null) { tempFile = Files.createTempFile("extension-out", ".tmp"); try (FileOutputStream out = new FileOutputStream(tempFile.toFile())) { body.transferTo(out); } } } return new SimpleHttpClientCachedResponse( HttpUtils.callSuccessful(response), response.statusCode(), response.headers().map(), tempFile != null ? tempFile.toAbsolutePath().toString() : null); }
Example 6
Source File: HttpClientExample.java From tutorials with MIT License | 5 votes |
public static void httpPostRequest() throws URISyntaxException, IOException, InterruptedException { HttpClient client = HttpClient.newBuilder() .version(HttpClient.Version.HTTP_2) .build(); HttpRequest request = HttpRequest.newBuilder(new URI("http://jsonplaceholder.typicode.com/posts")) .version(HttpClient.Version.HTTP_2) .POST(BodyPublishers.ofString("Sample Post Request")) .build(); HttpResponse<String> response = client.send(request, BodyHandlers.ofString()); String responseBody = response.body(); System.out.println("httpPostRequest : " + responseBody); }
Example 7
Source File: SimpleHttpClient.java From tcMenu with Apache License 2.0 | 5 votes |
@Override public byte[] postRequestForBinaryData(String url, String parameter, HttpDataType reqDataType) throws IOException, InterruptedException { HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(url)) .timeout(Duration.ofSeconds(20)) .header("Content-Type", toContentType(reqDataType)) .POST(HttpRequest.BodyPublishers.ofString(parameter)) .build(); HttpResponse<byte[]> response = client.send(request, HttpResponse.BodyHandlers.ofByteArray()); if(response.statusCode() != HTTP_SUCCESS) throw new IOException("Call returned bad status " + response.statusCode()); return response.body(); }
Example 8
Source File: SimpleHttpClient.java From tcMenu with Apache License 2.0 | 5 votes |
@Override public String postRequestForString(String url, String parameter, HttpDataType reqDataType) throws IOException, InterruptedException { HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(url)) .timeout(Duration.ofSeconds(20)) .header("Content-Type", toContentType(reqDataType)) .POST(HttpRequest.BodyPublishers.ofString(parameter)) .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); if(response.statusCode() != HTTP_SUCCESS) throw new IOException("Call returned bad status " + response.statusCode()); return response.body(); }
Example 9
Source File: JdkHttpClientService.java From mutual-tls-ssl with Apache License 2.0 | 5 votes |
@Override public ClientResponse executeRequest(String url) throws IOException, InterruptedException { HttpRequest request = HttpRequest.newBuilder() .GET() .header(HEADER_KEY_CLIENT_TYPE, getClientType().getValue()) .uri(URI.create(url)) .build(); HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); return new ClientResponse(response.body(), response.statusCode()); }
Example 10
Source File: HttpClientExample.java From tutorials with MIT License | 5 votes |
public static void httpGetRequest() throws URISyntaxException, IOException, InterruptedException { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .version(HttpClient.Version.HTTP_2) .uri(URI.create("http://jsonplaceholder.typicode.com/posts/1")) .headers("Accept-Enconding", "gzip, deflate") .build(); HttpResponse<String> response = client.send(request, BodyHandlers.ofString()); String responseBody = response.body(); int responseStatusCode = response.statusCode(); System.out.println("httpGetRequest: " + responseBody); System.out.println("httpGetRequest status code: " + responseStatusCode); }
Example 11
Source File: RestClient.java From r2cloud with Apache License 2.0 | 5 votes |
public String getFile(String url) { HttpResponse<String> response = getFileResponse(url); if (response.statusCode() != 200) { LOG.info("response: {}", response.body()); throw new RuntimeException("invalid status code: " + response.statusCode()); } return response.body(); }
Example 12
Source File: MavenRepositoryClient.java From vespa with Apache License 2.0 | 5 votes |
@Override public Metadata metadata() { try { HttpRequest request = HttpRequest.newBuilder(withArtifactPath(apiUrl, id)).build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString(UTF_8)); if (response.statusCode() != 200) throw new RuntimeException("Status code '" + response.statusCode() + "' and body\n'''\n" + response.body() + "\n'''\nfor request " + request); return Metadata.fromXml(response.body()); } catch (IOException | InterruptedException e) { throw new RuntimeException(e); } }
Example 13
Source File: SimpleHttpClient.java From alf.io with GNU General Public License v3.0 | 5 votes |
private SimpleHttpClientResponse callRemote(HttpRequest request) throws IOException { HttpResponse<String> response = null; try { response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); } catch (InterruptedException exception) { Thread.currentThread().interrupt(); logInterruption(exception); } return new SimpleHttpClientResponse( HttpUtils.callSuccessful(response), response.statusCode(), response.headers().map(), response.body()); }
Example 14
Source File: RecaptchaService.java From alf.io with GNU General Public License v3.0 | 5 votes |
private static boolean recaptchaRequest(HttpClient client, String secret, String response) { if(response == null) { return false; } try { var params = Map.of("secret", secret, "response", response); HttpResponse<String> httpResponse = HttpUtils.postForm(client, "https://www.google.com/recaptcha/api/siteverify", params); String body = httpResponse.body(); return body != null && Json.fromJson(body, RecatpchaResponse.class).success; } catch (IOException | InterruptedException e) { return false; } }
Example 15
Source File: ControllerHttpClient.java From vespa with Apache License 2.0 | 4 votes |
/** Returns the response body as a String, or throws if the status code is non-2XX. */ private static String asString(HttpResponse<byte[]> response) { return new String(response.body(), UTF_8); }
Example 16
Source File: Main.java From Java-Coding-Problems with MIT License | 4 votes |
public static void main(String[] args) throws IOException, InterruptedException { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://reqres.in/api/users/2")) .build(); // HttpResponse.BodyHandlers.ofString() HttpResponse<String> responseOfString = client.send( request, HttpResponse.BodyHandlers.ofString()); System.out.println("HttpResponse.BodyHandlers.ofString():"); System.out.println("Status code: " + responseOfString.statusCode()); System.out.println("Body: " + responseOfString.body()); // HttpResponse.BodyHandlers.ofFile() HttpResponse<Path> responseOfFile = client.send( request, HttpResponse.BodyHandlers.ofFile(Path.of("response.json"))); System.out.println("\nHttpResponse.BodyHandlers.ofFile():"); System.out.println("Status code: " + responseOfFile.statusCode()); System.out.println("Body: " + responseOfFile.body()); // HttpResponse.BodyHandlers.ofByteArray() HttpResponse<byte[]> responseOfByteArray = client.send( request, HttpResponse.BodyHandlers.ofByteArray()); System.out.println("\nHttpResponse.BodyHandlers.ofByteArray():"); System.out.println("Status code: " + responseOfByteArray.statusCode()); System.out.println("Body: " + new String(responseOfByteArray.body())); // HttpResponse.BodyHandlers.ofLines() HttpResponse<Stream<String>> responseOfLines = client.send( request, HttpResponse.BodyHandlers.ofLines()); System.out.println("\nHttpResponse.BodyHandlers.ofLines():"); System.out.println("Status code: " + responseOfLines.statusCode()); System.out.println("Body: " + responseOfLines.body().collect(toList())); // HttpResponse.BodyHandlers.ofInputStream() HttpResponse<InputStream> responseOfInputStream = client.send( request, HttpResponse.BodyHandlers.ofInputStream()); System.out.println("\nHttpResponse.BodyHandlers.ofInputStream():"); System.out.println("Status code: " + responseOfInputStream.statusCode()); byte[] allBytes; try ( InputStream fromIs = responseOfInputStream.body()) { allBytes = fromIs.readAllBytes(); } System.out.println("Body: " + new String(allBytes, StandardCharsets.UTF_8)); }
Example 17
Source File: OreKitDataClient.java From r2cloud with Apache License 2.0 | 4 votes |
private void downloadAndSaveTo(String url, Path dst) throws IOException { Path tempPath = dst.getParent().resolve(dst.getFileName() + ".tmp").normalize(); if (Files.exists(tempPath) && !Util.deleteDirectory(tempPath)) { throw new RuntimeException("unable to delete tmp directory: " + tempPath); } Files.createDirectories(tempPath); Builder result = HttpRequest.newBuilder().uri(URI.create(url)); result.timeout(Duration.ofMillis(TIMEOUT)); result.header("User-Agent", R2Cloud.getVersion() + " [email protected]"); HttpRequest request = result.build(); try { HttpResponse<InputStream> response = httpclient.send(request, BodyHandlers.ofInputStream()); if (response.statusCode() != 200) { throw new IOException("invalid status code: " + response.statusCode()); } Optional<String> contentType = response.headers().firstValue("Content-Type"); if (contentType.isEmpty() || !contentType.get().equals("application/zip")) { throw new IOException("Content-Type is empty or unsupported: " + contentType); } try (ZipInputStream zis = new ZipInputStream(response.body())) { ZipEntry zipEntry = null; while ((zipEntry = zis.getNextEntry()) != null) { Path destFile = tempPath.resolve(zipEntry.getName()).normalize(); if (!destFile.startsWith(tempPath)) { throw new IOException("invalid archive. zip slip detected: " + destFile); } if (zipEntry.isDirectory()) { Files.createDirectories(destFile); continue; } if (!Files.exists(destFile.getParent())) { Files.createDirectories(destFile.getParent()); } Files.copy(zis, destFile, StandardCopyOption.REPLACE_EXISTING); } Files.move(tempPath, dst, StandardCopyOption.REPLACE_EXISTING); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(e); } }
Example 18
Source File: Main.java From Java-Coding-Problems with MIT License | 4 votes |
public static void main(String[] args) throws IOException, InterruptedException { Jsonb jsonb = JsonbBuilder.create(); HttpClient client = HttpClient.newHttpClient(); System.out.println("-------------------------------------"); System.out.println("-------------Get a user--------------"); System.out.println("-------------------------------------"); HttpRequest requestGet = HttpRequest.newBuilder() .uri(URI.create("https://reqres.in/api/users/2")) .build(); HttpResponse<User> responseGet = client.send(requestGet, JsonBodyHandler.jsonBodyHandler(jsonb, User.class)); System.out.println("Status code: " + responseGet.statusCode()); User user = responseGet.body(); System.out.println(user); System.out.println(); System.out.println("-------------------------------------"); System.out.println("-------------Update user-------------"); System.out.println("-------------------------------------"); user.getData().setEmail("[email protected]"); HttpRequest requestPut = HttpRequest.newBuilder() .header("Content-Type", "application/json") .uri(URI.create("https://reqres.in/api/users")) .PUT(HttpRequest.BodyPublishers.ofString(jsonb.toJson(user))) .build(); HttpResponse<User> responsePut = client.send( requestPut, JsonBodyHandler.jsonBodyHandler(jsonb, User.class)); System.out.println("Status code: " + responsePut.statusCode()); User updatedUser = responsePut.body(); System.out.println(updatedUser); System.out.println(); System.out.println("-------------------------------------"); System.out.println("-------------Post new user------------"); System.out.println("-------------------------------------"); Data data = new Data(); data.setId(10); data.setFirstName("John"); data.setLastName("Year"); data.setAvatar("https://johnyear.com/jy.png"); User newUser = new User(); newUser.setData(data); HttpRequest requestPost = HttpRequest.newBuilder() .header("Content-Type", "application/json") .uri(URI.create("https://reqres.in/api/users")) .POST(HttpRequest.BodyPublishers.ofString(jsonb.toJson(user))) .build(); HttpResponse<Void> responsePost = client.send( requestPost, HttpResponse.BodyHandlers.discarding()); System.out.println("Status code: " + responsePost.statusCode()); }