java.net.http.HttpResponse Java Examples

The following examples show how to use java.net.http.HttpResponse. 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: HttpServerTest.java    From piranha with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
/**
 * Test processing.
 *
 * @throws Exception when an error occurs.
 */
@Test
public void testProcessing() 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 #2
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 {

        System.out.println("Downloading (please wait) ...");

        HttpClient client = HttpClient.newHttpClient();

        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("http://demo.borland.com/testsite/downloads/downloadfile.php?file=Hello.txt&cd=attachment+filename"))
                .build();

        HttpResponse<Path> response = client.send(
                request, HttpResponse.BodyHandlers
                        .ofFileDownload(Path.of(System.getProperty("user.dir")), CREATE, WRITE));

        System.out.println("Status code: " + response.statusCode());
        System.out.println("\n Body: " + response.body());
    }
 
Example #3
Source File: FakeApi.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
/**
 * 
 * For this test, the body for this request much reference a schema named &#x60;File&#x60;.
 * @param body  (required)
 * @throws ApiException if fails to make API call
 */
public CompletableFuture<Void> testBodyWithFileSchema(FileSchemaTestClass body) throws ApiException {
  try {
    HttpRequest.Builder localVarRequestBuilder = testBodyWithFileSchemaRequestBuilder(body);
    return memberVarHttpClient.sendAsync(
            localVarRequestBuilder.build(),
            HttpResponse.BodyHandlers.ofString()).thenComposeAsync(localVarResponse -> {
        if (localVarResponse.statusCode()/ 100 != 2) {
            return CompletableFuture.failedFuture(new ApiException(localVarResponse.statusCode(),
                "testBodyWithFileSchema call received non-success response",
                localVarResponse.headers(),
                localVarResponse.body())
            );
        } else {
            return CompletableFuture.completedFuture(null);
        }
    });
  }
  catch (ApiException e) {
    return CompletableFuture.failedFuture(e);
  }
}
 
Example #4
Source File: HttpServerTest.java    From piranha with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 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 #5
Source File: UserRestClient.java    From Mastering-Microservices-with-Java-Third-Edition with MIT License 6 votes vote down vote up
public void putUser() throws Exception {
  UserVO userVO = new UserVO();
  userVO.setId("3");
  userVO.setName("X User 1");
  userVO.setAddress("X Address 1");
  userVO.setCity("X City 1");
  userVO.setPhoneNo("1234567899");
  HttpRequest request = restClient.requestBuilder(
      URI.create(userEndpoint + "/3"),
      Optional.empty()
  ).PUT(BodyPublishers.ofString(objectMapper.writeValueAsString(userVO))).build();
  HttpResponse<String> response = restClient.send(request);
  LOG.info("Response status code: {}", response.statusCode());
  LOG.info("Response headers: {}", response.headers());
  LOG.info("Response body: {}", response.body());
}
 
Example #6
Source File: HttpServiceTest.java    From elepy with Apache License 2.0 6 votes vote down vote up
@Test
void responses_HaveProperInputStream() throws IOException, InterruptedException {
    service.get("/input-stream", context -> {
        context.response().result(inputStream("cv.pdf"));
    });


    service.ignite();

    var request = HttpRequest.newBuilder()
            .uri(URI.create("http://localhost:3030/input-stream"))
            .GET()
            .build();

    final var send = httpClient.send(request, HttpResponse
            .BodyHandlers.ofInputStream());

    assertThat(IOUtils.contentEquals(inputStream("cv.pdf"), send.body()))
            .isTrue();
}
 
Example #7
Source File: HttpServerTest.java    From piranha with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 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 #8
Source File: NewService.java    From Pixiv-Illustration-Collection-Backend with Apache License 2.0 6 votes vote down vote up
private void pullFUTA404News() throws IOException, InterruptedException {
    HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("http://www.futa404.com/category/dmaz")).GET().build();
    String body = httpClient.send(request, HttpResponse.BodyHandlers.ofString()).body();
    Document doc = Jsoup.parse(body);
    Elements elements = doc.getElementsByClass("card flex-fill mb-4 mb-sm-4-2 mb-md-4 mb-lg-4-2");
    List<ACGNew> acgNewList = elements.stream().map(e -> {
        String cover = e.getElementsByClass("lazyload custom-hover-img original").get(0).attr("src");
        Element t = e.getElementsByClass("custom-hover d-block").get(0);
        String title = t.attr("title");
        String rerfererUrl = t.attr("href");
        String time = e.getElementsByClass("u-time").get(0).text();
        LocalDate createDate;
        if (time.contains("-")) {
            createDate = LocalDate.parse(time);
        } else {
            createDate = LocalDate.now();
        }
        String intro = e.getElementsByClass("text-l2 font-md-12 text-secondary").get(0).text();
        return new ACGNew(title, intro, NewsCrawlerConstant.FUTA404, cover, rerfererUrl, createDate, NewsCrawlerConstant.FUTA404);
    }).collect(Collectors.toList());
    process(acgNewList, "class", "post-content suxing-popup-gallery");
}
 
Example #9
Source File: FakeApi.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
/**
 * Fake endpoint for testing various parameters  假端點  偽のエンドポイント  가짜 엔드 포인트
 * Fake endpoint for testing various parameters  假端點  偽のエンドポイント  가짜 엔드 포인트
 * @param number None (required)
 * @param _double None (required)
 * @param patternWithoutDelimiter None (required)
 * @param _byte None (required)
 * @param integer None (optional)
 * @param int32 None (optional)
 * @param int64 None (optional)
 * @param _float None (optional)
 * @param string None (optional)
 * @param binary None (optional)
 * @param date None (optional)
 * @param dateTime None (optional)
 * @param password None (optional)
 * @param paramCallback None (optional)
 * @throws ApiException if fails to make API call
 */
public CompletableFuture<Void> testEndpointParameters(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, File binary, LocalDate date, OffsetDateTime dateTime, String password, String paramCallback) throws ApiException {
  try {
    HttpRequest.Builder localVarRequestBuilder = testEndpointParametersRequestBuilder(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback);
    return memberVarHttpClient.sendAsync(
            localVarRequestBuilder.build(),
            HttpResponse.BodyHandlers.ofString()).thenComposeAsync(localVarResponse -> {
        if (localVarResponse.statusCode()/ 100 != 2) {
            return CompletableFuture.failedFuture(new ApiException(localVarResponse.statusCode(),
                "testEndpointParameters call received non-success response",
                localVarResponse.headers(),
                localVarResponse.body())
            );
        } else {
            return CompletableFuture.completedFuture(null);
        }
    });
  }
  catch (ApiException e) {
    return CompletableFuture.failedFuture(e);
  }
}
 
Example #10
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 #11
Source File: ExampleIntegrationTest.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@Test
public void helloHttp_shouldRunWithFunctionsFramework() throws Throwable {
  String functionUrl = BASE_URL + "/helloHttp";

  HttpRequest getRequest = HttpRequest.newBuilder().uri(URI.create(functionUrl)).GET().build();

  // The Functions Framework Maven plugin process takes time to start up
  // Use resilience4j to retry the test HTTP request until the plugin responds
  RetryRegistry registry = RetryRegistry.of(RetryConfig.custom()
      .maxAttempts(8)
      .intervalFunction(IntervalFunction.ofExponentialBackoff(200, 2))
      .retryExceptions(IOException.class)
      .build());
  Retry retry = registry.retry("my");

  // Perform the request-retry process
  String body = Retry.decorateCheckedSupplier(retry, () -> client.send(
      getRequest,
      HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8)).body()
  ).apply();

  // Verify the function returned the right results
  assertThat(body).isEqualTo("Hello world!");
}
 
Example #12
Source File: BangumiCrawlerService.java    From Pixiv-Illustration-Collection-Backend with Apache License 2.0 6 votes vote down vote up
private List<Integer> querySubjectId(Integer pageNum) throws IOException, InterruptedException {
    List<Integer> idList = new ArrayList<>(24);
    int currentIndex = 0;
    //开始查找id并添加到文件
    for (; currentIndex < pageNum; currentIndex++) {
        System.out.println("开始爬取第" + currentIndex + "页");
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://bangumi.tv/anime/browser/?sort=date&page=" + currentIndex)).GET().build();
        String body = httpClient.send(request, HttpResponse.BodyHandlers.ofString()).body();
        //jsoup提取文本
        Document doc = Jsoup.parse(body);
        Elements elements = doc.getElementsByClass("subjectCover cover ll");
        elements.forEach(e -> {
            idList.add(Integer.parseInt(e.attr("href").replaceAll("\\D", "") + "\n"));
        });
    }
    return idList;
}
 
Example #13
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 #14
Source File: NewService.java    From Pixiv-Illustration-Collection-Backend with Apache License 2.0 6 votes vote down vote up
private void pullACG17News() throws IOException, InterruptedException {
    HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("http://acg17.com/category/news/")).GET().build();
    String body = httpClient.send(request, HttpResponse.BodyHandlers.ofString()).body();
    Document doc = Jsoup.parse(body);
    Elements elements = doc.getElementsByClass("item-list");
    List<ACGNew> acgNewList = elements.stream().map(e -> {
        String style = e.getElementsByClass("attachment-tie-medium size-tie-medium wp-post-image").get(0).attr("style");
        String cover = style.substring(style.indexOf("url(") + 4, style.indexOf(")"));
        Element t = e.getElementsByClass("post-box-title").get(0).child(0);
        LocalDate createDate = LocalDate.parse(e.getElementsByClass("tie-date").get(0).text().replaceAll("[年月]", "-").replace("日", ""));
        String intro = e.getElementsByClass("entry").get(0).child(0).text();
        String title = t.text();
        String rerfererUrl = t.attr("href");
        return new ACGNew(title, intro, NewsCrawlerConstant.ACG17, cover, rerfererUrl, createDate, NewsCrawlerConstant.ACG17);
    }).collect(Collectors.toList());
    process(acgNewList, "class", "entry");
}
 
Example #15
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()
                .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 #16
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 #17
Source File: ExternalMessageSignerService.java    From teku with Apache License 2.0 6 votes vote down vote up
private BLSSignature getBlsSignature(
    final HttpResponse<String> response, final Throwable throwable) {
  if (throwable != null) {
    throw new ExternalSignerException(
        "External signer failed to sign due to " + throwable.getMessage(), throwable);
  }

  if (response.statusCode() != 200) {
    throw new ExternalSignerException(
        "External signer failed to sign and returned invalid response status code: "
            + response.statusCode());
  }

  try {
    final Bytes signature = Bytes.fromHexString(response.body());
    return BLSSignature.fromBytes(signature);
  } catch (final IllegalArgumentException e) {
    throw new ExternalSignerException(
        "External signer returned an invalid signature: " + e.getMessage(), e);
  }
}
 
Example #18
Source File: UserApi.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
/**
 * Create user
 * This can only be done by the logged in user.
 * @param body Created user object (required)
 * @throws ApiException if fails to make API call
 */
public CompletableFuture<Void> createUser(User body) throws ApiException {
  try {
    HttpRequest.Builder localVarRequestBuilder = createUserRequestBuilder(body);
    return memberVarHttpClient.sendAsync(
            localVarRequestBuilder.build(),
            HttpResponse.BodyHandlers.ofString()).thenComposeAsync(localVarResponse -> {
        if (localVarResponse.statusCode()/ 100 != 2) {
            return CompletableFuture.failedFuture(new ApiException(localVarResponse.statusCode(),
                "createUser call received non-success response",
                localVarResponse.headers(),
                localVarResponse.body())
            );
        } else {
            return CompletableFuture.completedFuture(null);
        }
    });
  }
  catch (ApiException e) {
    return CompletableFuture.failedFuture(e);
  }
}
 
Example #19
Source File: FakeApi.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
/**
 * creates an XmlItem
 * this route creates an XmlItem
 * @param xmlItem XmlItem Body (required)
 * @throws ApiException if fails to make API call
 */
public CompletableFuture<Void> createXmlItem(XmlItem xmlItem) throws ApiException {
  try {
    HttpRequest.Builder localVarRequestBuilder = createXmlItemRequestBuilder(xmlItem);
    return memberVarHttpClient.sendAsync(
            localVarRequestBuilder.build(),
            HttpResponse.BodyHandlers.ofString()).thenComposeAsync(localVarResponse -> {
        if (localVarResponse.statusCode()/ 100 != 2) {
            return CompletableFuture.failedFuture(new ApiException(localVarResponse.statusCode(),
                "createXmlItem call received non-success response",
                localVarResponse.headers(),
                localVarResponse.body())
            );
        } else {
            return CompletableFuture.completedFuture(null);
        }
    });
  }
  catch (ApiException e) {
    return CompletableFuture.failedFuture(e);
  }
}
 
Example #20
Source File: RequestUtil.java    From Pixiv-Illustration-Collection-Backend with Apache License 2.0 6 votes vote down vote up
public CompletableFuture<String> getJson(String url) {
    HttpRequest.Builder uri = HttpRequest.newBuilder()
            .uri(URI.create(url));
    decorateHeader(uri);
    PixivUser pixivUser = oauthManager.getRandomPixivUser();
    HttpRequest getRank = uri
            .header("Authorization", "Bearer " + pixivUser.getAccessToken())
            .GET()
            .build();
    return httpClient.sendAsync(getRank, HttpResponse.BodyHandlers.ofString()).thenApply(resp -> {
        int code = resp.statusCode();
        //System.out.println(resp.body().length());
        if (code == 403) {
            pixivUser.ban();
            return "false";
        }
        return resp.body();
    });
}
 
Example #21
Source File: FakeApi.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
/**
 * 
 * To test the collection format in query parameters
 * @param pipe  (required)
 * @param ioutil  (required)
 * @param http  (required)
 * @param url  (required)
 * @param context  (required)
 * @throws ApiException if fails to make API call
 */
public CompletableFuture<Void> testQueryParameterCollectionFormat(List<String> pipe, List<String> ioutil, List<String> http, List<String> url, List<String> context) throws ApiException {
  try {
    HttpRequest.Builder localVarRequestBuilder = testQueryParameterCollectionFormatRequestBuilder(pipe, ioutil, http, url, context);
    return memberVarHttpClient.sendAsync(
            localVarRequestBuilder.build(),
            HttpResponse.BodyHandlers.ofString()).thenComposeAsync(localVarResponse -> {
        if (localVarResponse.statusCode()/ 100 != 2) {
            return CompletableFuture.failedFuture(new ApiException(localVarResponse.statusCode(),
                "testQueryParameterCollectionFormat call received non-success response",
                localVarResponse.headers(),
                localVarResponse.body())
            );
        } else {
            return CompletableFuture.completedFuture(null);
        }
    });
  }
  catch (ApiException e) {
    return CompletableFuture.failedFuture(e);
  }
}
 
Example #22
Source File: UserApi.java    From openapi-generator with Apache License 2.0 6 votes vote down vote up
/**
 * Logs out current logged in user session
 * 
 * @throws ApiException if fails to make API call
 */
public CompletableFuture<Void> logoutUser() throws ApiException {
  try {
    HttpRequest.Builder localVarRequestBuilder = logoutUserRequestBuilder();
    return memberVarHttpClient.sendAsync(
            localVarRequestBuilder.build(),
            HttpResponse.BodyHandlers.ofString()).thenComposeAsync(localVarResponse -> {
        if (localVarResponse.statusCode()/ 100 != 2) {
            return CompletableFuture.failedFuture(new ApiException(localVarResponse.statusCode(),
                "logoutUser call received non-success response",
                localVarResponse.headers(),
                localVarResponse.body())
            );
        } else {
            return CompletableFuture.completedFuture(null);
        }
    });
  }
  catch (ApiException e) {
    return CompletableFuture.failedFuture(e);
  }
}
 
Example #23
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 #24
Source File: HttpResponseUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void shouldReturnStatusOKWhenSendGetRequest() throws IOException, InterruptedException, URISyntaxException {
    HttpRequest request = HttpRequest.newBuilder()
        .uri(new URI("https://postman-echo.com/get"))
        .version(HttpClient.Version.HTTP_2)
        .GET()
        .build();

    HttpResponse<String> response = HttpClient.newBuilder()
        .followRedirects(HttpClient.Redirect.NORMAL)
        .build()
        .send(request, HttpResponse.BodyHandlers.ofString());

    assertThat(response.statusCode(), equalTo(HttpURLConnection.HTTP_OK));
    assertNotNull(response.body());
}
 
Example #25
Source File: HttpClientExamples.java    From hellokoding-courses with MIT License 6 votes vote down vote up
@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 #26
Source File: Example.java    From java11-examples with MIT License 5 votes vote down vote up
public static void uploadFile() throws Exception {
    HttpClient client = HttpClient.newHttpClient();


    HttpRequest request = HttpRequest.newBuilder()
            .uri(new URI("http://localhost:8080/upload/"))
            .POST(HttpRequest.BodyPublishers.ofFile(Paths.get("/tmp/files-to-upload.txt")))
            .build();

    HttpResponse<Void> response = client.send(request, HttpResponse.BodyHandlers.discarding());
    System.out.println(response.statusCode());
}
 
Example #27
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 #28
Source File: HttpClientDemo.java    From Learn-Java-12-Programming with MIT License 5 votes vote down vote up
private static void applyPushPromise(HttpRequest initReq, HttpRequest pushReq,
                            Function<BodyHandler, CompletableFuture<HttpResponse>> acceptor) {
    CompletableFuture<Void> cf = acceptor.apply(BodyHandlers.ofString())
            .thenAccept(resp -> System.out.println("Got pushed response " + resp.uri()));
    try {
        System.out.println("Pushed completableFuture get: " + cf.get(1, TimeUnit.SECONDS));
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    System.out.println("Exit the applyPushPromise function...");
}
 
Example #29
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 #30
Source File: ImagesJDBCTemplateDao.java    From crate-sample-apps with Apache License 2.0 5 votes vote down vote up
@Override
public InputStream getImageAsInputStream(final String digest) {
    var request = HttpRequest.newBuilder(this.createBlobUri(digest)).GET().build();
    try {
        var response = client.send(request, HttpResponse.BodyHandlers.ofInputStream());
        return response.body();
    } catch (IOException | InterruptedException e) {
        throw new DataIntegrityViolationException("Failed to call blob endpoint", e);
    }
}