java.net.http.HttpResponse.BodyHandlers Java Examples

The following examples show how to use java.net.http.HttpResponse.BodyHandlers. 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: R2ServerClient.java    From r2cloud with Apache License 2.0 8 votes vote down vote up
private void upload(String url, File file, String contentType) {
	HttpRequest request;
	try {
		request = createRequest(url).header("Content-Type", contentType).PUT(BodyPublishers.ofFile(file.toPath())).build();
	} catch (FileNotFoundException e) {
		LOG.error("unable to upload: {}", url, e);
		return;
	}
	httpclient.sendAsync(request, BodyHandlers.ofString()).exceptionally(ex -> {
		Util.logIOException(LOG, "unable to upload: " + url, ex);
		return null;
	}).thenAccept(response -> {
		if (response != null && response.statusCode() != 200 && LOG.isErrorEnabled()) {
			LOG.error("unable to upload: {} response code: {}. response: {}", url, response.statusCode(), response.body());
		}
	});
}
 
Example #2
Source File: HttpClientUnitTest.java    From tutorials with MIT License 7 votes vote down vote up
@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 #3
Source File: Http2Client.java    From feign with Apache License 2.0 6 votes vote down vote up
@Override
public Response execute(Request request, Options options) throws IOException {
  final HttpRequest httpRequest = newRequestBuilder(request).build();

  HttpResponse<byte[]> httpResponse;
  try {
    httpResponse = client.send(httpRequest, BodyHandlers.ofByteArray());
  } catch (final InterruptedException e) {
    throw new IOException("Invalid uri " + request.url(), e);
  }

  final OptionalLong length = httpResponse.headers().firstValueAsLong("Content-Length");

  final Response response = Response.builder()
      .body(new ByteArrayInputStream(httpResponse.body()),
          length.isPresent() ? (int) length.getAsLong() : null)
      .reason(httpResponse.headers().firstValue("Reason-Phrase").orElse("OK"))
      .request(request)
      .status(httpResponse.statusCode())
      .headers(castMapCollectType(httpResponse.headers().map()))
      .build();
  return response;
}
 
Example #4
Source File: JavaNetHttpRequester.java    From algoliasearch-client-java-2 with MIT License 6 votes vote down vote up
/**
 * Sends the http request asynchronously to the API If the request is time out it creates a new
 * response object with timeout set to true Otherwise it throws a run time exception
 *
 * @param request the request to send
 * @throws AlgoliaRuntimeException When an error occurred processing the request on the server
 *     side
 */
public CompletableFuture<HttpResponse> performRequestAsync(@Nonnull HttpRequest request) {
  return client
      .sendAsync(buildRequest(request), BodyHandlers.ofInputStream())
      .thenApply(this::buildResponse)
      .exceptionally(
          t -> {
            if (t.getCause() instanceof HttpConnectTimeoutException
                || t.getCause() instanceof HttpTimeoutException) {
              return new HttpResponse(true);
            } else if (t.getCause() instanceof SecurityException
                || t.getCause() instanceof IOException
                || t.getCause() instanceof InterruptedException) {
              return new HttpResponse().setNetworkError(true);
            }
            throw new AlgoliaRuntimeException(t);
          });
}
 
Example #5
Source File: Http2Api.java    From demo-java-x with MIT License 6 votes vote down vote up
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 #6
Source File: HttpClientExample.java    From tutorials with MIT License 6 votes vote down vote up
public static void pushRequest() throws URISyntaxException, InterruptedException {
    System.out.println("Running HTTP/2 Server Push example...");

    HttpClient httpClient = HttpClient.newBuilder()
        .version(Version.HTTP_2)
        .build();

    HttpRequest pageRequest = HttpRequest.newBuilder()
        .uri(URI.create("https://http2.golang.org/serverpush"))
        .build();

    // Interface HttpResponse.PushPromiseHandler<T>
    // void applyPushPromise​(HttpRequest initiatingRequest, HttpRequest pushPromiseRequest, Function<HttpResponse.BodyHandler<T>,​CompletableFuture<HttpResponse<T>>> acceptor)
    httpClient.sendAsync(pageRequest, BodyHandlers.ofString(), pushPromiseHandler())
        .thenAccept(pageResponse -> {
            System.out.println("Page response status code: " + pageResponse.statusCode());
            System.out.println("Page response headers: " + pageResponse.headers());
            String responseBody = pageResponse.body();
            System.out.println(responseBody);
        }).join();

    Thread.sleep(1000); // waiting for full response
}
 
Example #7
Source File: HttpClientUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@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 #8
Source File: Library.java    From 30-seconds-of-java with MIT License 6 votes vote down vote up
/**
 * Performs HTTP POST request.
 * Credits https://stackoverflow.com/questions/3324717/sending-http-post-request-in-java
 * @param address the URL of the connection in String format, like "http://www.google.com"
 * @param arguments the body of the POST request, as a HashMap
 * @return response object
 * @throws IOException if an I/O error occurs
 * @throws InterruptedException if the operation is interrupted
 */
public static HttpResponse<String> httpPost(String address, HashMap<String, String> arguments)
    throws IOException, InterruptedException {
  var sj = new StringJoiner("&");
  for (var entry : arguments.entrySet()) {
    sj.add(URLEncoder.encode(entry.getKey(), "UTF-8") + "="
        + URLEncoder.encode(entry.getValue(), "UTF-8"));
  }
  var out = sj.toString().getBytes(StandardCharsets.UTF_8);
  var request = HttpRequest.newBuilder()
      .uri(URI.create(address))
      .headers("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
      .POST(BodyPublishers.ofByteArray(out))
      .build();

  return HttpClient.newHttpClient().send(request, BodyHandlers.ofString());
}
 
Example #9
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 #10
Source File: HttpClientUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void shouldFollowRedirectWhenSetToAlways() throws IOException, InterruptedException, URISyntaxException {
    HttpRequest request = HttpRequest.newBuilder()
        .uri(new URI("http://stackoverflow.com"))
        .version(HttpClient.Version.HTTP_1_1)
        .GET()
        .build();
    HttpResponse<String> response = HttpClient.newBuilder()
        .followRedirects(HttpClient.Redirect.ALWAYS)
        .build()
        .send(request, HttpResponse.BodyHandlers.ofString());

    assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
    assertThat(response.request()
        .uri()
        .toString(), equalTo("https://stackoverflow.com/"));
}
 
Example #11
Source File: HttpClientUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@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: HaveIBeenPwned.java    From passpol with Apache License 2.0 6 votes vote down vote up
@Override
public boolean contains(String password) throws IOException {
  try {
    var hash = hex(MessageDigest.getInstance("SHA1").digest(PasswordPolicy.normalize(password)));
    var request =
        HttpRequest.newBuilder()
            .GET()
            .uri(BASE_URI.resolve(hash.substring(0, PREFIX_LENGTH)))
            .header("User-Agent", "passpol")
            .build();
    var response = client.send(request, BodyHandlers.ofLines());
    if (response.statusCode() != 200) {
      throw new IOException("Unexpected response from server: " + response.statusCode());
    }
    return response
        .body()
        .filter(s -> s.regionMatches(0, hash, PREFIX_LENGTH, SUFFIX_LENGTH))
        .map(s -> s.substring(HASH_LENGTH + DELIM_LENGTH))
        .mapToInt(Integer::parseInt)
        .anyMatch(t -> t >= threshold);
  } catch (NoSuchAlgorithmException | InterruptedException | IndexOutOfBoundsException e) {
    throw new IOException(e);
  }
}
 
Example #13
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 #14
Source File: HttpClientDemo.java    From Learn-Java-12-Programming with MIT License 6 votes vote down vote up
private static void postAsync(){
    HttpClient httpClient = HttpClient.newHttpClient();

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

    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 #15
Source File: HttpClientDemo.java    From Learn-Java-12-Programming with MIT License 6 votes vote down vote up
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 #16
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 #17
Source File: HttpClientUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void shouldNotStoreCookieWhenPolicyAcceptNone() 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_NONE))
        .build();

    httpClient.send(request, HttpResponse.BodyHandlers.ofString());

    assertTrue(httpClient.cookieHandler()
        .isPresent());
}
 
Example #18
Source File: ExternalMessageSignerService.java    From teku with Apache License 2.0 6 votes vote down vote up
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 #19
Source File: ScriptFinder.java    From burp-javascript-security-extension with GNU General Public License v3.0 6 votes vote down vote up
/**
 * There is no reason that this should ever be called within burp. It is just here for tests.
 * This uses incubated JDK libraries
 */
public void retrieveHtml(){
    if (!url.equals("NONE")){
        HttpClient client = HttpClient.newBuilder().followRedirects(HttpClient.Redirect.ALWAYS).build();
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create(url))
            .build();
        try {
            HttpResponse<String> response = client.send(request, BodyHandlers.ofString());
            setHtml(response.body());
        }
        catch (Exception ex) {
            System.err.println("[-] There was an issue getting the JavaScript file at " + url);
            System.err.println(ex.toString());
            ex.printStackTrace();
        }
    }
}
 
Example #20
Source File: Requester.java    From burp-javascript-security-extension with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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 #21
Source File: HttpClientUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void shouldSendRequestAsync() throws URISyntaxException, InterruptedException, ExecutionException {
    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();
    CompletableFuture<HttpResponse<String>> response = HttpClient.newBuilder()
        .build()
        .sendAsync(request, HttpResponse.BodyHandlers.ofString());

    assertThat(response.get()
        .statusCode(), equalTo(HttpURLConnection.HTTP_OK));
}
 
Example #22
Source File: HttpClientUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void shouldUseJustTwoThreadWhenProcessingSendAsyncRequest() throws URISyntaxException, InterruptedException, ExecutionException {
    HttpRequest request = HttpRequest.newBuilder()
        .uri(new URI("https://postman-echo.com/get"))
        .GET()
        .build();

    ExecutorService executorService = Executors.newFixedThreadPool(2);

    CompletableFuture<HttpResponse<String>> response1 = HttpClient.newBuilder()
        .executor(executorService)
        .build()
        .sendAsync(request, HttpResponse.BodyHandlers.ofString());

    CompletableFuture<HttpResponse<String>> response2 = HttpClient.newBuilder()
        .executor(executorService)
        .build()
        .sendAsync(request, HttpResponse.BodyHandlers.ofString());

    CompletableFuture<HttpResponse<String>> response3 = HttpClient.newBuilder()
        .executor(executorService)
        .build()
        .sendAsync(request, HttpResponse.BodyHandlers.ofString());

    CompletableFuture.allOf(response1, response2, response3)
        .join();

    assertThat(response1.get()
        .statusCode(), equalTo(HttpURLConnection.HTTP_OK));
    assertThat(response2.get()
        .statusCode(), equalTo(HttpURLConnection.HTTP_OK));
    assertThat(response3.get()
        .statusCode(), equalTo(HttpURLConnection.HTTP_OK));
}
 
Example #23
Source File: HttpClientUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void shouldNotFollowRedirectWhenSetToDefaultNever() throws IOException, InterruptedException, URISyntaxException {
    HttpRequest request = HttpRequest.newBuilder()
        .uri(new URI("http://stackoverflow.com"))
        .version(HttpClient.Version.HTTP_1_1)
        .GET()
        .build();
    HttpResponse<String> response = HttpClient.newBuilder()
        .build()
        .send(request, HttpResponse.BodyHandlers.ofString());

    assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_MOVED_PERM));
    assertThat(response.body(), containsString("https://stackoverflow.com/"));
}
 
Example #24
Source File: HttpClientExample.java    From tutorials with MIT License 5 votes vote down vote up
private static PushPromiseHandler<String> pushPromiseHandler() {
    return (HttpRequest initiatingRequest, 
        HttpRequest pushPromiseRequest, 
        Function<HttpResponse.BodyHandler<String>, 
        CompletableFuture<HttpResponse<String>>> acceptor) -> {
        acceptor.apply(BodyHandlers.ofString())
            .thenAccept(resp -> {
                System.out.println(" Pushed response: " + resp.uri() + ", headers: " + resp.headers());
            });
        System.out.println("Promise request: " + pushPromiseRequest.uri());
        System.out.println("Promise request: " + pushPromiseRequest.headers());
    };
}
 
Example #25
Source File: HttpClientUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void shouldProcessMultipleRequestViaStream() throws URISyntaxException, ExecutionException, InterruptedException {
    List<URI> targets = Arrays.asList(new URI("https://postman-echo.com/get?foo1=bar1"), new URI("https://postman-echo.com/get?foo2=bar2"));

    HttpClient client = HttpClient.newHttpClient();

    List<CompletableFuture<String>> futures = targets.stream()
        .map(target -> client.sendAsync(HttpRequest.newBuilder(target)
            .GET()
            .build(), HttpResponse.BodyHandlers.ofString())
            .thenApply(response -> response.body()))
        .collect(Collectors.toList());

    CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]))
        .join();

    if (futures.get(0)
        .get()
        .contains("foo1")) {
        assertThat(futures.get(0)
            .get(), containsString("bar1"));
        assertThat(futures.get(1)
            .get(), containsString("bar2"));
    } else {
        assertThat(futures.get(1)
            .get(), containsString("bar2"));
        assertThat(futures.get(1)
            .get(), containsString("bar1"));
    }

}
 
Example #26
Source File: ReactivePost.java    From demo-java-x with MIT License 5 votes vote down vote up
public static void main(String[] args) throws IOException, InterruptedException {
	HttpClient client = HttpClient.newBuilder().build();
	HttpRequest post = HttpRequest
			.newBuilder(POSTMAN_POST)
			.POST(new LoggingBodyPublisher(BodyPublishers.ofFile(LARGE_JSON)))
			.header("Content-Type", "application/json")
			.build();
	HttpResponse<String> response = client
			.send(post, BodyHandlers.ofString());

	System.out.println("Status: " + response.statusCode());
	System.out.println(response.body());
}
 
Example #27
Source File: HttpClientExample.java    From tutorials with MIT License 5 votes vote down vote up
public static void asynchronousMultipleRequests() throws URISyntaxException {
    HttpClient client = HttpClient.newHttpClient();
    List<URI> uris = Arrays.asList(new URI("http://jsonplaceholder.typicode.com/posts/1"), new URI("http://jsonplaceholder.typicode.com/posts/2"));
    List<HttpRequest> requests = uris.stream()
        .map(HttpRequest::newBuilder)
        .map(reqBuilder -> reqBuilder.build())
        .collect(Collectors.toList());
    System.out.println("Got pushed response1 " + requests);
    CompletableFuture.allOf(requests.stream()
        .map(request -> client.sendAsync(request, BodyHandlers.ofString()))
        .toArray(CompletableFuture<?>[]::new))
        .thenAccept(System.out::println)
        .join();
}
 
Example #28
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 #29
Source File: HttpClientExample.java    From tutorials with MIT License 5 votes vote down vote up
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 #30
Source File: HttpClientExample.java    From tutorials with MIT License 5 votes vote down vote up
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);
}