Java Code Examples for java.net.http.HttpClient#newHttpClient()

The following examples show how to use java.net.http.HttpClient#newHttpClient() . 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: DefaultWebApplicationServerTest.java    From piranha with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 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 2
Source File: ClientEndpoint.java    From conga with Apache License 2.0 6 votes vote down vote up
/**
 * Opens a WebSocket to the server
 *
 * @throws Exception complete exceptionally with one of the following errors:
 *         <ul>
 *         <li>{@link IOException} - if an I/O error occurs
 *         <li>{@link WebSocketHandshakeException} - if the opening handshake fails
 *         <li>{@link HttpTimeoutException} - if the opening handshake does not complete within
 *         the timeout
 *         <li>{@link InterruptedException} - if the operation is interrupted
 *         <li>{@link SecurityException} - if a security manager has been installed and it denies
 *         {@link java.net.URLPermission access} to {@code uri}.
 *         <a href="HttpRequest.html#securitychecks">Security checks</a> contains more information
 *         relating to the security context in which the the listener is invoked.
 *         <li>{@link IllegalArgumentException} - if any of the arguments to the constructor are
 *         invalid
 *         </ul>
 * 
 */
public void open() throws Exception {
  while (!connectedCriticalSection.compareAndSet(false, true)) {
    Thread.yield();
  }
  try {
    if (webSocket == null) {
      final HttpClient httpClient = HttpClient.newHttpClient();
      webSocket = httpClient.newWebSocketBuilder().subprotocols(subprotocol)
          .connectTimeout(Duration.ofSeconds(timeoutSeconds)).buildAsync(uri, listener).get();
      final SSLSessionContext clientSessionContext =
          httpClient.sslContext().getClientSessionContext();
      byte[] id = clientSessionContext.getIds().nextElement();
      SSLSession sslSession = clientSessionContext.getSession(id);
      Principal principal = sslSession.getLocalPrincipal();
      source = (null != principal) ? principal.getName() : new String(id);
    }
  } finally {
    connectedCriticalSection.compareAndSet(true, false);
  }
}
 
Example 3
Source File: GitHub.java    From jmbe with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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 4
Source File: MicroPiranhaTest.java    From piranha with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 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 5
Source File: Main.java    From Java-Coding-Problems with MIT License 6 votes vote down vote up
public static void main(String[] args) throws IOException, InterruptedException {

        HttpClient client = HttpClient.newHttpClient();

        HttpRequest request = HttpRequest.newBuilder()
                .headers("Content-Type", "application/json")
                .header("Referer", "https://reqres.in/")
                .setHeader("X-Auth", "authtoken")
                .uri(URI.create("https://reqres.in/api/users/2"))
                .build();

        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

        HttpHeaders allHeaders = response.headers();        
        System.out.println("All headers: " + allHeaders);                       
        
        List<String> allValuesOfCacheControl = response.headers().allValues("Cache-Control");                        
        System.out.println("All values of Cache-Control: " + allValuesOfCacheControl);                       
        
        Optional<String> firstValueOfCacheControl = response.headers().firstValue("Cache-Control");
        System.out.println("First value of Cache-Control: " + firstValueOfCacheControl);                       
    }
 
Example 6
Source File: FindVehicleCommand.java    From exonum-java-binding with Apache License 2.0 6 votes vote down vote up
@Override
public Integer call() throws Exception {
  var serviceName = findServiceName();
  var httpClient = HttpClient.newHttpClient();
  var findVehicleRequest = HttpRequest.newBuilder()
      .uri(buildRequestUri(serviceName))
      .GET()
      .build();
  var response = httpClient.send(findVehicleRequest, BodyHandlers.ofByteArray());
  var statusCode = response.statusCode();
  if (statusCode == HTTP_OK) {
    var vehicle = Vehicle.parseFrom(response.body());
    System.out.println("Vehicle: " + vehicle);
    return 0;
  } else if (statusCode == HTTP_NOT_FOUND) {
    System.out.printf("Vehicle with id (%s) is not found.%n", vehicleId);
    return statusCode;
  } else {
    System.out.println("Status code: " + statusCode);
    return statusCode;
  }
}
 
Example 7
Source File: HttpServerTest.java    From piranha with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 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 8
Source File: HttpClientExamples.java    From java8-tutorial with MIT License 6 votes vote down vote up
private static void basicAuth() throws IOException, InterruptedException {
    var client = HttpClient.newHttpClient();

    var request1 = HttpRequest.newBuilder()
            .uri(URI.create("https://postman-echo.com/basic-auth"))
            .build();
    var response1 = client.send(request1, HttpResponse.BodyHandlers.ofString());
    System.out.println(response1.statusCode());      // 401

    var authClient = HttpClient
            .newBuilder()
            .authenticator(new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication("postman", "password".toCharArray());
                }
            })
            .build();
    var request2 = HttpRequest.newBuilder()
            .uri(URI.create("https://postman-echo.com/basic-auth"))
            .build();
    var response2 = authClient.send(request2, HttpResponse.BodyHandlers.ofString());
    System.out.println(response2.statusCode());      // 200
}
 
Example 9
Source File: HttpClientDemo.java    From Learn-Java-12-Programming with MIT License 6 votes vote down vote up
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 10
Source File: HttpClientDemo.java    From Learn-Java-12-Programming with MIT License 6 votes vote down vote up
private static void get(){
        HttpClient httpClient = HttpClient.newHttpClient();
/*
        HttpClient httpClient = HttpClient.newBuilder()
                .version(HttpClient.Version.HTTP_2)  // default
                .build();
*/

        HttpRequest req = HttpRequest.newBuilder()
                .uri(URI.create("http://localhost:3333/something"))
                .GET()   // default
                .build();

        try {
            HttpResponse<String> resp = httpClient.send(req, BodyHandlers.ofString());
            System.out.println("Response: " + resp.statusCode() + " : " + resp.body());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
 
Example 11
Source File: HttpClientDemo.java    From Learn-Java-12-Programming with MIT License 5 votes vote down vote up
private static void post(){
    HttpClient httpClient = HttpClient.newHttpClient();

    HttpRequest req = HttpRequest.newBuilder()
            .uri(URI.create("http://localhost:3333/something"))
            .POST(BodyPublishers.ofString("Hi there!"))
            .build();

    try {
        HttpResponse<String> resp = httpClient.send(req, BodyHandlers.ofString());
        System.out.println("Response: " + resp.statusCode() + " : " + resp.body());
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}
 
Example 12
Source File: ViaHeader.java    From Java-Coding-Problems with MIT License 5 votes vote down vote up
public void headerExample() throws IOException, InterruptedException {

        HttpClient client = HttpClient.newHttpClient();

        HttpRequest request = HttpRequest.newBuilder()
                .header("Authorization", basicAuth("username", "password"))
                // ...
                .build();

        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
    }
 
Example 13
Source File: Main.java    From Java-Coding-Problems with MIT License 5 votes vote down vote up
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"))
                .timeout(Duration.of(5, ChronoUnit.MILLIS))
                .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 14
Source File: Example.java    From java11-examples with MIT License 5 votes vote down vote up
public void getURIs(List<URI> uris) {
    HttpClient client = HttpClient.newHttpClient();
    List<HttpRequest> requests = uris.stream()
            .map(HttpRequest::newBuilder)
            .map(HttpRequest.Builder::build)
            .collect(toList());

    CompletableFuture.allOf(requests.stream()
            .map(request -> client.sendAsync(request, HttpResponse.BodyHandlers.ofString()))
            .toArray(CompletableFuture<?>[]::new))
            .join();
}
 
Example 15
Source File: WebSocketServiceTest.java    From mangooio with Apache License 2.0 5 votes vote down vote up
@Test
public void testSendDataWithInvalidAuthentication() throws Exception {
    // given
    final HttpClient httpClient = HttpClient.newHttpClient();
    final Config config = Application.getInstance(Config.class);
    final String url = "ws://" + config.getConnectorHttpHost() + ":" + config.getConnectorHttpPort() + "/websocketauth";
    final String data = UUID.randomUUID().toString();
    eventData = null;
    
    PasetoV1LocalBuilder token = Pasetos.V1.LOCAL.builder().setSubject("foo")
            .setExpiration(LocalDateTime.now().plusHours(1).atZone(ZoneId.systemDefault()).toInstant())
            .claim(ClaimKey.TWO_FACTOR.toString(), "false")
            .setSharedSecret(new SecretKeySpec("oskdlwsodkcmansjdkwsowekd5jfvsq2mckdkalsodkskajsfdsfdsfvvkdkcskdsqidsjk".getBytes(StandardCharsets.UTF_8), "AES"));
    
    Listener listener = new Listener() {
        @Override
        public CompletionStage<?> onText(WebSocket webSocket, CharSequence message, boolean last) {
            eventData = message.toString();
            return null;
        }
    };
    httpClient.newWebSocketBuilder()
        .header("Cookie", config.getAuthenticationCookieName() + "=" + token.compact())
        .buildAsync(new URI(url), listener);
    
    await().atMost(2, TimeUnit.SECONDS).untilAsserted(() -> assertThat(eventData, not(equalTo(data))));
    
    Application.getInstance(WebSocketService.class).getChannels("/websocketauth").forEach(channel -> {
        try {
            if (channel.isOpen()) {
                WebSockets.sendTextBlocking(data, channel);
            }
        } catch (final IOException e) {
            e.printStackTrace();
        }
     });
    
    // then
    await().atMost(2, TimeUnit.SECONDS).untilAsserted(() -> assertThat(eventData, not(equalTo(data)))); 
}
 
Example 16
Source File: HttpClientExample.java    From tutorials with MIT License 5 votes vote down vote up
public static void asynchronousGetRequest() throws URISyntaxException {
    HttpClient client = HttpClient.newHttpClient();
    URI httpURI = new URI("http://jsonplaceholder.typicode.com/posts/1");
    HttpRequest request = HttpRequest.newBuilder(httpURI)
        .version(HttpClient.Version.HTTP_2)
        .build();
    CompletableFuture<Void> futureResponse = client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
        .thenAccept(resp -> {
            System.out.println("Got pushed response " + resp.uri());
            System.out.println("Response statuscode: " + resp.statusCode());
            System.out.println("Response body: " + resp.body());
        });
    System.out.println("futureResponse" + futureResponse);

}
 
Example 17
Source File: SyncRequest.java    From Java-Coding-Problems with MIT License 5 votes vote down vote up
public void triggerSyncRequest() 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("Status code: " + response.statusCode());
    System.out.println("\n Body: " + response.body());
}
 
Example 18
Source File: WaitAllResponsesDisplayBodies.java    From Java-Coding-Problems with MIT License 5 votes vote down vote up
public void waitAllResponses() 
        throws URISyntaxException, InterruptedException, ExecutionException {

    List<URI> uris = Arrays.asList(
            new URI("https://reqres.in/api/users/2"),      // one user
            new URI("https://reqres.in/api/users?page=2"), // list of users
            new URI("https://reqres.in/api/unknown/2"),    // list of resources
            new URI("https://reqres.in/api/users/23"));    // single user not foud

    HttpClient client = HttpClient.newHttpClient();

    List<HttpRequest> requests = uris.stream()
            .map(HttpRequest::newBuilder)
            .map(reqBuilder -> reqBuilder.build())
            .collect(Collectors.toList());

    CompletableFuture.allOf(requests.stream()
            .map(req -> client.sendAsync(req, HttpResponse.BodyHandlers.ofString())
            .thenApply((res) -> res.uri() + " | " + res.body() + "\n")
            .exceptionally(e -> "Exception: " + e)
            .thenAccept(System.out::println))
            .toArray(CompletableFuture<?>[]::new))
            .join();

    // or, written like this
    /*
    CompletableFuture<?>[] responses = requests.stream()
            .map(req -> client.sendAsync(req, HttpResponse.BodyHandlers.ofString())
            .thenApply((res) -> res.uri() + " | " + res.body() + "\n")
            .exceptionally(e -> "Exception: " + e)
            .thenAccept(System.out::println))
            .toArray(CompletableFuture<?>[]::new);

    CompletableFuture.allOf(responses).join();
    */
}
 
Example 19
Source File: HttpClientExamples.java    From hellokoding-courses with MIT License 5 votes vote down vote up
@Test
public void createADefaultHTTPClient() {
    HttpClient client = HttpClient.newHttpClient();

    assertThat(client.version()).isEqualTo(HttpClient.Version.HTTP_2);
    assertThat(client.followRedirects()).isEqualTo(HttpClient.Redirect.NEVER);
    assertThat(client.proxy()).isEmpty();
    assertThat(client.connectTimeout()).isEmpty();
    assertThat(client.cookieHandler()).isEmpty();
    assertThat(client.authenticator()).isEmpty();
    assertThat(client.executor()).isEmpty();
}
 
Example 20
Source File: WaitAllResponsesFetchBodiesInList.java    From Java-Coding-Problems with MIT License 4 votes vote down vote up
public void waitAllResponses()
        throws URISyntaxException, InterruptedException, ExecutionException {

    List<URI> uris = Arrays.asList(
            new URI("https://reqres.in/api/users/2"),      // one user
            new URI("https://reqres.in/api/users?page=2"), // list of users
            new URI("https://reqres.in/api/unknown/2"),    // list of resources
            new URI("https://reqres.in/api/users/23"));    // single user not foud

    HttpClient client = HttpClient.newHttpClient();

    List<HttpRequest> requests = uris.stream()
            .map(HttpRequest::newBuilder)
            .map(reqBuilder -> reqBuilder.build())
            .collect(Collectors.toList());

    @SuppressWarnings("unchecked")
    CompletableFuture<String>[] arrayResponses = requests.stream()
            .map(req -> asyncResponse(client, req))
            .toArray(CompletableFuture[]::new);

    CompletableFuture<Void> responses = CompletableFuture.allOf(arrayResponses);

    while (!responses.isDone()) {
        Thread.sleep(50);
        System.out.println("Waiting for all responses ...");
    }

    responses.get(); // eventually, add a timeout

    List<String> results = responses.thenApply(e -> {

        List<String> bodies = new ArrayList<>();
        for (CompletableFuture<String> body : arrayResponses) {
            bodies.add(body.join());
        }

        return bodies;
    }).get();

    results.forEach(System.out::println);
}