java.net.http.HttpClient Java Examples
The following examples show how to use
java.net.http.HttpClient.
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: Main.java From Java-Coding-Problems with MIT License | 8 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<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println("Version: " + response.version()); System.out.println("\nURI: " + response.uri()); System.out.println("\nStatus code: " + response.statusCode()); System.out.println("\nHeaders: " + response.headers()); System.out.println("\n Body: " + response.body()); }
Example #2
Source File: WebSocketControllerTest.java From mangooio with Apache License 2.0 | 7 votes |
@Test public void testWebSocketConnection() throws Exception { // given final HttpClient httpClient = HttpClient.newHttpClient(); final Config config = Application.getInstance(Config.class); final String uri = "ws://" + config.getConnectorHttpHost() + ":" + config.getConnectorHttpPort() + "/websocket"; // when Listener listener = new Listener() { @Override public void onOpen(WebSocket webSocket) { connected = true; } }; httpClient.newWebSocketBuilder().buildAsync(new URI(uri), listener).join(); // then assertThat(connected, equalTo(true)); }
Example #3
Source File: ViaAuthenticator.java From Java-Coding-Problems with MIT License | 7 votes |
public void authenticatorExample() throws IOException, InterruptedException { HttpClient client = HttpClient.newBuilder() .authenticator(new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication( "username", "password".toCharArray()); } }).build(); HttpRequest request = HttpRequest.newBuilder() // ... .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); }
Example #4
Source File: HttpClientUnitTest.java From tutorials with MIT License | 7 votes |
@Test public void shouldStoreCookieWhenPolicyAcceptAll() throws URISyntaxException, IOException, InterruptedException { HttpRequest request = HttpRequest.newBuilder() .uri(new URI("https://postman-echo.com/get")) .GET() .build(); HttpClient httpClient = HttpClient.newBuilder() .cookieHandler(new CookieManager(null, CookiePolicy.ACCEPT_ALL)) .build(); httpClient.send(request, HttpResponse.BodyHandlers.ofString()); assertTrue(httpClient.cookieHandler() .isPresent()); }
Example #5
Source File: TelegramNotifier.java From blog-tutorials with MIT License | 6 votes |
public static void main(String[] args) throws IOException, InterruptedException { String message = "Hello World from Java 11"; HttpClient client = HttpClient.newBuilder() .connectTimeout(Duration.ofSeconds(5)) .version(HttpClient.Version.HTTP_2) .build(); UriBuilder builder = UriBuilder .fromUri("https://api.telegram.org") .path("/{token}/sendMessage") .queryParam("chat_id", CHAT_ID) .queryParam("text", message); HttpRequest request = HttpRequest.newBuilder() .GET() .uri(builder.build("bot" + TOKEN)) .timeout(Duration.ofSeconds(5)) .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode()); System.out.println(response.body()); }
Example #6
Source File: Main.java From Java-Coding-Problems with MIT License | 6 votes |
public static void main(String[] args) throws IOException, InterruptedException { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://http2.golang.org/serverpush")) .build(); client.sendAsync(request, HttpResponse.BodyHandlers.ofString(), pushPromiseHandler()) .thenApply(HttpResponse::body) .thenAccept((b) -> System.out.println("\nMain resource:\n" + b)) .join(); System.out.println("\nPush promises map size: " + promisesMap.size() + "\n"); promisesMap.entrySet().forEach((entry) -> { System.out.println("Request = " + entry.getKey() + ", \nResponse = " + entry.getValue().join().body()); }); }
Example #7
Source File: Http2Api.java From demo-java-x with MIT License | 6 votes |
private static CompletableFuture<Void> reactiveSearch(HttpClient client, URI url, String term) { HttpRequest request = HttpRequest.newBuilder() .GET() .uri(url) .build(); StringFinder finder = new StringFinder(term); client.sendAsync(request, BodyHandlers.fromLineSubscriber(finder)) .exceptionally(ex -> { finder.onError(ex); return null; }); return finder .found() .exceptionally(Http2Api::handleError) .thenAccept(found -> handleResult(url, found)); }
Example #8
Source File: Main.java From Java-Coding-Problems with MIT License | 6 votes |
public static void main(String[] args) throws IOException, InterruptedException { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .header("Accept-Encoding", "gzip") .uri(URI.create("https://davidwalsh.name")) .build(); HttpResponse<InputStream> response = client.send( request, HttpResponse.BodyHandlers.ofInputStream()); System.out.println("Status code: " + response.statusCode()); String encoding = response.headers().firstValue("Content-Encoding").orElse(""); System.out.println("\nEncoding: " + encoding + "\n"); if ("gzip".equals(encoding)) { String gzipAsString = gzipToString(response.body()); System.out.println(gzipAsString); } else { String isAsString = isToString(response.body()); System.out.println(isAsString); } }
Example #9
Source File: Main.java From Java-Coding-Problems with MIT License | 6 votes |
public static void main(String[] args) throws IOException, InterruptedException { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://http2.golang.org/serverpush")) .build(); client.sendAsync(request, HttpResponse.BodyHandlers.ofString(), pushPromiseHandler()) .thenApply(HttpResponse::body) .thenAccept((b) -> System.out.println("\nMain resource:\n" + b)) .join(); asyncPushRequests.forEach(CompletableFuture::join); System.out.println("\nFetched a total of " + asyncPushRequests.size() + " push requests"); }
Example #10
Source File: ViaBody.java From Java-Coding-Problems with MIT License | 6 votes |
public void bodyExample() throws IOException, InterruptedException { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .header("Content-Type", "application/json") .POST(BodyPublishers.ofString( "{\"email\":\"[email protected]\",\"password\":\"cityslicka\"}")) .uri(URI.create("https://reqres.in/api/login")) .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println("Status code: " + response.statusCode()); System.out.println("\n Body: " + response.body()); }
Example #11
Source File: HttpClientUnitTest.java From tutorials with MIT License | 6 votes |
@Test public void shouldReturnOKStatusForAuthenticatedAccess() throws URISyntaxException, IOException, InterruptedException { HttpRequest request = HttpRequest.newBuilder() .uri(new URI("https://postman-echo.com/basic-auth")) .GET() .build(); HttpResponse<String> response = HttpClient.newBuilder() .authenticator(new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("postman", "password".toCharArray()); } }) .build() .send(request, HttpResponse.BodyHandlers.ofString()); assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK)); }
Example #12
Source File: MicroPiranhaTest.java From piranha with BSD 3-Clause "New" or "Revised" License | 6 votes |
/** * Test changing port. * * @throws Exception when an error occurs. */ @Test @Disabled public void testChangingPort() throws Exception { System.setProperty("java.naming.factory.initial", "cloud.piranha.jndi.memory.DefaultInitialContextFactory"); final MicroPiranha piranha = new MicroPiranha(); piranha.configure(new String[]{"--port", "8088"}); Thread thread = new Thread(piranha); thread.start(); Thread.sleep(3000); try { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder(URI.create("http://localhost:8088/does-not-exist")).build(); HttpResponse<Void> response = client.send(request, HttpResponse.BodyHandlers.discarding()); assertEquals(response.statusCode(), 404); } catch (IOException ioe) { throw new RuntimeException(ioe); } piranha.stop(); Thread.sleep(3000); }
Example #13
Source File: HttpClientUnitTest.java From tutorials with MIT License | 6 votes |
@Test public void shouldReturnSampleDataContentWhenConnectViaSystemProxy() throws IOException, InterruptedException, URISyntaxException { HttpRequest request = HttpRequest.newBuilder() .uri(new URI("https://postman-echo.com/post")) .headers("Content-Type", "text/plain;charset=UTF-8") .POST(HttpRequest.BodyPublishers.ofString("Sample body")) .build(); HttpResponse<String> response = HttpClient.newBuilder() .proxy(ProxySelector.getDefault()) .build() .send(request, HttpResponse.BodyHandlers.ofString()); assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK)); assertThat(response.body(), containsString("Sample body")); }
Example #14
Source File: HttpServerTest.java From piranha with BSD 3-Clause "New" or "Revised" License | 6 votes |
/** * Test file not found. * * @throws Exception when an error occurs. */ @Test public void testFileNotFound() throws Exception { HttpServer server = createServer(8765); server.start(); try { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder(URI.create("http://localhost:8765/this_is_certainly_not_there")).build(); HttpResponse<Void> response = client.send(request, HttpResponse.BodyHandlers.discarding()); assertEquals(response.statusCode(), 404); } catch (IOException ioe) { throw new RuntimeException(ioe); } finally { server.stop(); } }
Example #15
Source File: DefaultHttpServerTest.java From piranha with BSD 3-Clause "New" or "Revised" License | 6 votes |
/** * Test SO_TIMEOUT. */ @Test public void testSoTimeout() { DefaultHttpServer server = new DefaultHttpServer( 8765, new DefaultHttpServerProcessor(), 2000); assertEquals(server.getSoTimeout(), 2000); server.start(); try { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder(URI.create("http://localhost:8765/")).build(); HttpResponse<Void> response = client.send(request, HttpResponse.BodyHandlers.discarding()); assertEquals(response.statusCode(), 200); } catch (IOException | InterruptedException ioe) { throw new RuntimeException(ioe); } finally { server.stop(); } }
Example #16
Source File: HttpClientExamples.java From hellokoding-courses with MIT License | 6 votes |
@Test public void postAsync() { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("http://localhost:8081/test/resource")) .header("Accept", "application/json") .POST(HttpRequest.BodyPublishers.ofString("ping!")) .build(); CompletableFuture<HttpResponse<String>> completableFuture = client.sendAsync(request, HttpResponse.BodyHandlers.ofString()); completableFuture .thenApplyAsync(HttpResponse::headers) .thenAcceptAsync(System.out::println); HttpResponse<String> response = completableFuture.join(); assertThat(response.statusCode()).isEqualTo(200); }
Example #17
Source File: HttpClientExamples.java From hellokoding-courses with MIT License | 6 votes |
@Test public void basicAuthentication() throws IOException, InterruptedException { HttpClient client = HttpClient.newHttpClient(); String encodedAuth = Base64.getEncoder() .encodeToString(("user" + ":" + "pass").getBytes(StandardCharsets.UTF_8)); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("http://localhost:8081/test/secure")) .header("Authorization", "Basic " + encodedAuth) .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); assertThat(response.statusCode()).isEqualTo(200); }
Example #18
Source File: GitHub.java From jmbe with GNU General Public License v3.0 | 6 votes |
/** * Obtain the latest release object from the repository. * @param repositoryURL for the GitHub api * @return the latest release or null */ public static Release getLatestRelease(String repositoryURL) { HttpClient httpClient = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder().uri(URI.create(repositoryURL)).build(); try { HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); if(response.statusCode() == 200) { return parseResponse(response.body()); } else { mLog.error("Error while fetching latest releases - HTTP:" + response.statusCode()); } } catch(IOException | InterruptedException e) { mLog.error("Error while detecting the current release version of JMBE library", e); } return null; }
Example #19
Source File: DefaultWebApplicationServerTest.java From piranha with BSD 3-Clause "New" or "Revised" License | 6 votes |
/** * Test process method. * * @throws Exception when a serious error occurs. */ @Test public void testProcess() throws Exception { DefaultWebApplicationServer server = new DefaultWebApplicationServer(); HttpServer httpServer = new DefaultHttpServer(8180, server, false); DefaultWebApplication application = new DefaultWebApplication(); application.setContextPath("/context"); application.addServlet("snoop", new TestSnoopServlet()); application.addServletMapping("snoop", "/snoop/*"); server.addWebApplication(application); server.initialize(); server.start(); httpServer.start(); try { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder(new URI("http://localhost:8180/context/snoop/index.html")).build(); HttpResponse<Void> response = client.send(request, HttpResponse.BodyHandlers.discarding()); assertEquals(response.statusCode(), 200); } catch (IOException ioe) { throw new RuntimeException(ioe); } httpServer.stop(); server.stop(); }
Example #20
Source File: ApiClient.java From openapi-generator with Apache License 2.0 | 6 votes |
/** * Ctor. */ public ApiClient() { builder = HttpClient.newBuilder(); mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); mapper.configure(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE, false); mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); mapper.registerModule(new JavaTimeModule()); JsonNullableModule jnm = new JsonNullableModule(); mapper.registerModule(jnm); URI baseURI = URI.create("http://petstore.swagger.io:80/v2"); scheme = baseURI.getScheme(); host = baseURI.getHost(); port = baseURI.getPort(); basePath = baseURI.getRawPath(); interceptor = null; readTimeout = null; responseInterceptor = null; }
Example #21
Source File: MicroPiranhaTest.java From piranha with BSD 3-Clause "New" or "Revised" License | 6 votes |
/** * Test start method. * * @throws Exception when an error occurs. */ @Test @Disabled public void testStart() throws Exception { System.setProperty("java.naming.factory.initial", "cloud.piranha.jndi.memory.DefaultInitialContextFactory"); final MicroPiranha piranha = new MicroPiranha(); piranha.configure(new String[]{}); Thread thread = new Thread(piranha); thread.start(); Thread.sleep(3000); try { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder(URI.create("http://localhost:8080/does-not-exist")).build(); HttpResponse<Void> response = client.send(request, HttpResponse.BodyHandlers.discarding()); assertEquals(response.statusCode(), 404); } catch (IOException ioe) { throw new RuntimeException(ioe); } piranha.stop(); Thread.sleep(3000); }
Example #22
Source File: HttpServerTest.java From piranha with BSD 3-Clause "New" or "Revised" License | 6 votes |
/** * Test processing. * * @throws Exception when an error occurs. */ @Test public void testProcessing2() throws Exception { HttpServer server = createServer(8765); server.start(); try { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder(URI.create("http://localhost:8765")).build(); HttpResponse<Void> response = client.send(request, HttpResponse.BodyHandlers.discarding()); assertEquals(response.statusCode(), 200); } catch (IOException ioe) { throw new RuntimeException(ioe); } finally { server.stop(); } }
Example #23
Source File: ExternalMessageSignerService.java From teku with Apache License 2.0 | 6 votes |
private SafeFuture<BLSSignature> sign(final Bytes signingRoot) { final String publicKey = blsPublicKey.getPublicKey().toString(); return SafeFuture.ofComposed( () -> { final String requestBody = createSigningRequestBody(signingRoot); final URI uri = signingServiceUrl.toURI().resolve("/signer/sign/" + publicKey); final HttpRequest request = HttpRequest.newBuilder() .uri(uri) .timeout(timeout) .POST(BodyPublishers.ofString(requestBody)) .build(); return HttpClient.newHttpClient() .sendAsync(request, BodyHandlers.ofString()) .handleAsync(this::getBlsSignature); }); }
Example #24
Source File: Example.java From java11-examples with MIT License | 6 votes |
public static void asyncGet(String uri) throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(uri)) .build(); CompletableFuture<HttpResponse<String>> responseCompletableFuture = client.sendAsync(request, HttpResponse.BodyHandlers.ofString()); responseCompletableFuture.whenComplete((resp, t) -> { if (t != null) { t.printStackTrace(); } else { System.out.println(resp.body()); System.out.println(resp.statusCode()); } }).join(); }
Example #25
Source File: HttpClientDemo.java From Learn-Java-12-Programming with MIT License | 6 votes |
private static void getAsync(){ HttpClient httpClient = HttpClient.newHttpClient(); HttpRequest req = HttpRequest.newBuilder() .uri(URI.create("http://localhost:3333/something")) .GET() // default .build(); /* CompletableFuture<Void> cf = httpClient.sendAsync(req, BodyHandlers.ofString()) .thenAccept(resp -> System.out.println("Response: " + resp.statusCode() + " : " + resp.body())); */ CompletableFuture<String> cf = httpClient.sendAsync(req, BodyHandlers.ofString()) .thenApply(resp -> "Server responded: " + resp.body()); System.out.println("The request was sent asynchronously..."); try { System.out.println("CompletableFuture get: " + cf.get(5, TimeUnit.SECONDS)); } catch (Exception ex) { ex.printStackTrace(); } System.out.println("Exit the client..."); }
Example #26
Source File: HttpClientDemo.java From Learn-Java-12-Programming with MIT License | 6 votes |
private static void push(){ HttpClient httpClient = HttpClient.newHttpClient(); HttpRequest req = HttpRequest.newBuilder() .uri(URI.create("http://localhost:3333/something")) .GET() .build(); CompletableFuture cf = httpClient.sendAsync(req, BodyHandlers.ofString(), (PushPromiseHandler) HttpClientDemo::applyPushPromise); System.out.println("The request was sent asynchronously..."); try { System.out.println("CompletableFuture get: " + cf.get(5, TimeUnit.SECONDS)); } catch (Exception ex) { ex.printStackTrace(); } System.out.println("Exit the client..."); }
Example #27
Source File: HttpClientExamples.java From hellokoding-courses with MIT License | 6 votes |
@Test public void postJson() throws IOException, InterruptedException { HttpClient client = HttpClient.newHttpClient(); Book book = new Book(1, "Java HttpClient in practice"); String body = objectMapper.writeValueAsString(book); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("http://localhost:8081/test/resource")) .header("Accept", "application/json") .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString(body)) .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); assertThat(response.statusCode()).isEqualTo(200); assertThat(objectMapper.readValue(response.body(), Book.class).id).isEqualTo(1); }
Example #28
Source File: Example.java From java11-examples with MIT License | 5 votes |
public static void downloadFile() throws Exception { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(new URI("https://labs.consol.de/")) .GET() .build(); Path tempFile = Files.createTempFile("consol-labs-home", ".html"); HttpResponse<Path> response = client.send(request, HttpResponse.BodyHandlers.ofFile(tempFile)); System.out.println(response.statusCode()); System.out.println(response.body()); }
Example #29
Source File: MicroPiranhaIT.java From piranha with BSD 3-Clause "New" or "Revised" License | 5 votes |
/** * Test the Piranha Micro command line. * * @throws Exception when a serious error occurs. */ @Test @Disabled public void testCommandLine() throws Exception { String version = System.getProperty("VERSION"); ProcessBuilder builder = new ProcessBuilder(); builder.command("java", "-jar", "target/piranha-micro-" + version + "-all.jar"); Process process = builder.start(); HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder(new URI("http://localhost:8080/")).build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); assertEquals(response.statusCode(), 404); process.destroyForcibly(); }
Example #30
Source File: HttpRequestUnitTest.java From tutorials with MIT License | 5 votes |
@Test public void shouldFallbackToHttp1_1WhenWebsiteDoesNotUseHttp2() throws IOException, InterruptedException, URISyntaxException, NoSuchAlgorithmException { HttpRequest request = HttpRequest.newBuilder() .uri(new URI("https://postman-echo.com/get")) .version(HttpClient.Version.HTTP_2) .GET() .build(); HttpResponse<String> response = HttpClient.newHttpClient() .send(request, HttpResponse.BodyHandlers.ofString()); assertThat(response.version(), equalTo(HttpClient.Version.HTTP_1_1)); }