java.net.http.HttpRequest Java Examples
The following examples show how to use
java.net.http.HttpRequest.
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 |
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: HttpServerTest.java From piranha with BSD 3-Clause "New" or "Revised" License | 7 votes |
/** * 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 #3
Source File: StoreApi.java From openapi-generator with Apache License 2.0 | 6 votes |
/** * Delete purchase order by ID * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors * @param orderId ID of the order that needs to be deleted (required) * @throws ApiException if fails to make API call */ public CompletableFuture<Void> deleteOrder(String orderId) throws ApiException { try { HttpRequest.Builder localVarRequestBuilder = deleteOrderRequestBuilder(orderId); return memberVarHttpClient.sendAsync( localVarRequestBuilder.build(), HttpResponse.BodyHandlers.ofString()).thenComposeAsync(localVarResponse -> { if (localVarResponse.statusCode()/ 100 != 2) { return CompletableFuture.failedFuture(new ApiException(localVarResponse.statusCode(), "deleteOrder 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: Example.java From java11-examples with MIT License | 6 votes |
public static void asyncPost() throws Exception { HttpClient client = HttpClient.newHttpClient(); Gson gson = new Gson(); Foo foo = new Foo(); foo.name = "王爵nice"; foo.url = "https://github.com/biezhi"; String jsonBody = gson.toJson(foo); HttpRequest request = HttpRequest.newBuilder() .uri(new URI("https://httpbin.org/post")) .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString(jsonBody)) .build(); client.sendAsync(request, HttpResponse.BodyHandlers.ofString()) .whenComplete((resp, t) -> { if (t != null) { t.printStackTrace(); } else { System.out.println(resp.body()); System.out.println(resp.statusCode()); } }).join(); }
Example #5
Source File: StoreApi.java From openapi-generator with Apache License 2.0 | 6 votes |
private HttpRequest.Builder deleteOrderRequestBuilder(String orderId) throws ApiException { // verify the required parameter 'orderId' is set if (orderId == null) { throw new ApiException(400, "Missing the required parameter 'orderId' when calling deleteOrder"); } HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); String localVarPath = "/store/order/{order_id}" .replace("{order_id}", ApiClient.urlEncode(orderId.toString())); localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath)); localVarRequestBuilder.header("Accept", "application/json"); localVarRequestBuilder.method("DELETE", HttpRequest.BodyPublishers.noBody()); if (memberVarReadTimeout != null) { localVarRequestBuilder.timeout(memberVarReadTimeout); } if (memberVarInterceptor != null) { memberVarInterceptor.accept(localVarRequestBuilder); } return localVarRequestBuilder; }
Example #6
Source File: RevolutBankTransferManager.java From alf.io with GNU General Public License v3.0 | 6 votes |
private List<String> loadAccountsFromAPI(String revolutKey, String baseUrl) { var request = HttpRequest.newBuilder(URI.create(baseUrl + "/api/1.0/accounts")) .GET() .header("Authorization", "Bearer "+revolutKey) .build(); try { var response = client.send(request, HttpResponse.BodyHandlers.ofString()); if(response.statusCode() == HttpStatus.OK.value()) { List<Map<String, ?>> result = Json.fromJson(response.body(), new TypeReference<>() {}); return result.stream().filter(m -> "active".equals(m.get("state"))).map(m -> (String) m.get("id")).collect(Collectors.toList()); } throw new IllegalStateException("cannot retrieve accounts"); } catch (Exception e) { log.warn("got error while retrieving accounts", e); throw new IllegalStateException(e); } }
Example #7
Source File: FakeApi.java From openapi-generator with Apache License 2.0 | 6 votes |
private HttpRequest.Builder fakeOuterStringSerializeRequestBuilder(String body) throws ApiException { HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); String localVarPath = "/fake/outer/string"; localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath)); localVarRequestBuilder.header("Content-Type", "application/json"); localVarRequestBuilder.header("Accept", "application/json"); try { byte[] localVarPostBody = memberVarObjectMapper.writeValueAsBytes(body); localVarRequestBuilder.method("POST", HttpRequest.BodyPublishers.ofByteArray(localVarPostBody)); } catch (IOException e) { throw new ApiException(e); } if (memberVarReadTimeout != null) { localVarRequestBuilder.timeout(memberVarReadTimeout); } if (memberVarInterceptor != null) { memberVarInterceptor.accept(localVarRequestBuilder); } return localVarRequestBuilder; }
Example #8
Source File: NewService.java From Pixiv-Illustration-Collection-Backend with Apache License 2.0 | 6 votes |
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: UserApi.java From openapi-generator with Apache License 2.0 | 6 votes |
/** * 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 #10
Source File: Example.java From java11-examples with MIT License | 6 votes |
public static void basicAuth() throws Exception { HttpClient client = HttpClient.newBuilder() .authenticator(new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("username", "password".toCharArray()); } }) .build(); HttpRequest request = HttpRequest.newBuilder() .uri(new URI("https://labs.consol.de")) .GET() .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode()); System.out.println(response.body()); }
Example #11
Source File: UserApi.java From openapi-generator with Apache License 2.0 | 6 votes |
private HttpRequest.Builder getUserByNameRequestBuilder(String username) throws ApiException { // verify the required parameter 'username' is set if (username == null) { throw new ApiException(400, "Missing the required parameter 'username' when calling getUserByName"); } HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); String localVarPath = "/user/{username}" .replace("{username}", ApiClient.urlEncode(username.toString())); localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath)); localVarRequestBuilder.header("Accept", "application/json"); localVarRequestBuilder.method("GET", HttpRequest.BodyPublishers.noBody()); if (memberVarReadTimeout != null) { localVarRequestBuilder.timeout(memberVarReadTimeout); } if (memberVarInterceptor != null) { memberVarInterceptor.accept(localVarRequestBuilder); } return localVarRequestBuilder; }
Example #12
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 #13
Source File: FakeApi.java From openapi-generator with Apache License 2.0 | 6 votes |
/** * test inline additionalProperties * * @param param request body (required) * @throws ApiException if fails to make API call */ public CompletableFuture<Void> testInlineAdditionalProperties(Map<String, String> param) throws ApiException { try { HttpRequest.Builder localVarRequestBuilder = testInlineAdditionalPropertiesRequestBuilder(param); return memberVarHttpClient.sendAsync( localVarRequestBuilder.build(), HttpResponse.BodyHandlers.ofString()).thenComposeAsync(localVarResponse -> { if (localVarResponse.statusCode()/ 100 != 2) { return CompletableFuture.failedFuture(new ApiException(localVarResponse.statusCode(), "testInlineAdditionalProperties call received non-success response", localVarResponse.headers(), localVarResponse.body()) ); } else { return CompletableFuture.completedFuture(null); } }); } catch (ApiException e) { return CompletableFuture.failedFuture(e); } }
Example #14
Source File: SimpleHttpClient.java From alf.io with GNU General Public License v3.0 | 6 votes |
private SimpleHttpClientCachedResponse callRemoteAndSaveResponse(HttpRequest request) throws IOException { HttpResponse<InputStream> response = null; try { response = httpClient.send(request, HttpResponse.BodyHandlers.ofInputStream()); } catch (InterruptedException exception) { Thread.currentThread().interrupt(); logInterruption(exception); } Path tempFile = null; if (HttpUtils.callSuccessful(response)) { InputStream body = response.body(); if (body != null) { tempFile = Files.createTempFile("extension-out", ".tmp"); try (FileOutputStream out = new FileOutputStream(tempFile.toFile())) { body.transferTo(out); } } } return new SimpleHttpClientCachedResponse( HttpUtils.callSuccessful(response), response.statusCode(), response.headers().map(), tempFile != null ? tempFile.toAbsolutePath().toString() : null); }
Example #15
Source File: PetApi.java From openapi-generator with Apache License 2.0 | 6 votes |
private HttpRequest.Builder updatePetWithFormRequestBuilder(Long petId, String name, String status) throws ApiException { // verify the required parameter 'petId' is set if (petId == null) { throw new ApiException(400, "Missing the required parameter 'petId' when calling updatePetWithForm"); } HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); String localVarPath = "/pet/{petId}" .replace("{petId}", ApiClient.urlEncode(petId.toString())); localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath)); localVarRequestBuilder.header("Accept", "application/json"); localVarRequestBuilder.method("POST", HttpRequest.BodyPublishers.noBody()); if (memberVarReadTimeout != null) { localVarRequestBuilder.timeout(memberVarReadTimeout); } if (memberVarInterceptor != null) { memberVarInterceptor.accept(localVarRequestBuilder); } return localVarRequestBuilder; }
Example #16
Source File: FakeApi.java From openapi-generator with Apache License 2.0 | 6 votes |
private HttpRequest.Builder fakeOuterStringSerializeRequestBuilder(String body) throws ApiException { HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); String localVarPath = "/fake/outer/string"; localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath)); localVarRequestBuilder.header("Content-Type", "application/json"); localVarRequestBuilder.header("Accept", "application/json"); try { byte[] localVarPostBody = memberVarObjectMapper.writeValueAsBytes(body); localVarRequestBuilder.method("POST", HttpRequest.BodyPublishers.ofByteArray(localVarPostBody)); } catch (IOException e) { throw new ApiException(e); } if (memberVarReadTimeout != null) { localVarRequestBuilder.timeout(memberVarReadTimeout); } if (memberVarInterceptor != null) { memberVarInterceptor.accept(localVarRequestBuilder); } return localVarRequestBuilder; }
Example #17
Source File: HttpServerTest.java From piranha with BSD 3-Clause "New" or "Revised" License | 6 votes |
/** * Test file. * * @throws Exception when a serious error occurs. */ @Test public void testFile() throws Exception { HttpServer server = createServer(8765); server.start(); try { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder(URI.create("http://localhost:8765/pom.xml")).build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8)); assertEquals(response.statusCode(), 200); String responseText = response.body(); assertTrue(responseText.contains("modelVersion")); } catch (IOException ioe) { throw new RuntimeException(ioe); } finally { server.stop(); } }
Example #18
Source File: PetApi.java From openapi-generator with Apache License 2.0 | 6 votes |
private HttpRequest.Builder updatePetWithFormRequestBuilder(Long petId, String name, String status) throws ApiException { // verify the required parameter 'petId' is set if (petId == null) { throw new ApiException(400, "Missing the required parameter 'petId' when calling updatePetWithForm"); } HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); String localVarPath = "/pet/{petId}" .replace("{petId}", ApiClient.urlEncode(petId.toString())); localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath)); localVarRequestBuilder.header("Accept", "application/json"); localVarRequestBuilder.method("POST", HttpRequest.BodyPublishers.noBody()); if (memberVarReadTimeout != null) { localVarRequestBuilder.timeout(memberVarReadTimeout); } if (memberVarInterceptor != null) { memberVarInterceptor.accept(localVarRequestBuilder); } return localVarRequestBuilder; }
Example #19
Source File: FakeApi.java From openapi-generator with Apache License 2.0 | 6 votes |
private HttpRequest.Builder fakeOuterBooleanSerializeRequestBuilder(Boolean body) throws ApiException { HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); String localVarPath = "/fake/outer/boolean"; localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath)); localVarRequestBuilder.header("Content-Type", "application/json"); localVarRequestBuilder.header("Accept", "application/json"); try { byte[] localVarPostBody = memberVarObjectMapper.writeValueAsBytes(body); localVarRequestBuilder.method("POST", HttpRequest.BodyPublishers.ofByteArray(localVarPostBody)); } catch (IOException e) { throw new ApiException(e); } if (memberVarReadTimeout != null) { localVarRequestBuilder.timeout(memberVarReadTimeout); } if (memberVarInterceptor != null) { memberVarInterceptor.accept(localVarRequestBuilder); } return localVarRequestBuilder; }
Example #20
Source File: Main.java From Java-Coding-Problems with MIT License | 6 votes |
private static HttpResponse.PushPromiseHandler<String> pushPromiseHandler() { return (HttpRequest initiatingRequest, HttpRequest pushPromiseRequest, Function<HttpResponse.BodyHandler<String>, CompletableFuture<HttpResponse<String>>> acceptor) -> { CompletableFuture<Void> pushcf = acceptor.apply(HttpResponse.BodyHandlers.ofString()) .thenApply(HttpResponse::body) .thenAccept((b) -> System.out.println("\nPushed resource body:\n " + b)); asyncPushRequests.add(pushcf); System.out.println("\nJust got promise push number: " + asyncPushRequests.size()); System.out.println("\nInitial push request: " + initiatingRequest.uri()); System.out.println("Initial push headers: " + initiatingRequest.headers()); System.out.println("Promise push request: " + pushPromiseRequest.uri()); System.out.println("Promise push headers: " + pushPromiseRequest.headers()); }; }
Example #21
Source File: UserApi.java From openapi-generator with Apache License 2.0 | 6 votes |
private HttpRequest.Builder deleteUserRequestBuilder(String username) throws ApiException { // verify the required parameter 'username' is set if (username == null) { throw new ApiException(400, "Missing the required parameter 'username' when calling deleteUser"); } HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); String localVarPath = "/user/{username}" .replace("{username}", ApiClient.urlEncode(username.toString())); localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath)); localVarRequestBuilder.header("Accept", "application/json"); localVarRequestBuilder.method("DELETE", HttpRequest.BodyPublishers.noBody()); if (memberVarReadTimeout != null) { localVarRequestBuilder.timeout(memberVarReadTimeout); } if (memberVarInterceptor != null) { memberVarInterceptor.accept(localVarRequestBuilder); } return localVarRequestBuilder; }
Example #22
Source File: FakeApi.java From openapi-generator with Apache License 2.0 | 6 votes |
/** * To test enum parameters * To test enum parameters * @param enumHeaderStringArray Header parameter enum test (string array) (optional * @param enumHeaderString Header parameter enum test (string) (optional, default to -efg) * @param enumQueryStringArray Query parameter enum test (string array) (optional * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) * @param enumQueryInteger Query parameter enum test (double) (optional) * @param enumQueryDouble Query parameter enum test (double) (optional) * @param enumFormStringArray Form parameter enum test (string array) (optional * @param enumFormString Form parameter enum test (string) (optional, default to -efg) * @throws ApiException if fails to make API call */ public CompletableFuture<Void> testEnumParameters(List<String> enumHeaderStringArray, String enumHeaderString, List<String> enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble, List<String> enumFormStringArray, String enumFormString) throws ApiException { try { HttpRequest.Builder localVarRequestBuilder = testEnumParametersRequestBuilder(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumFormStringArray, enumFormString); return memberVarHttpClient.sendAsync( localVarRequestBuilder.build(), HttpResponse.BodyHandlers.ofString()).thenComposeAsync(localVarResponse -> { if (localVarResponse.statusCode()/ 100 != 2) { return CompletableFuture.failedFuture(new ApiException(localVarResponse.statusCode(), "testEnumParameters 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: CollectionTagSearchUtil.java From Pixiv-Illustration-Collection-Backend with Apache License 2.0 | 6 votes |
public CompletableFuture<List<CollectionTag>> request(String body) { HttpRequest httpRequest = HttpRequest.newBuilder() .header("Content-Type", "application/json") .uri(URI.create("http://" + elasticsearch + ":9200/collection_tag/_search")) .method("GET", HttpRequest.BodyPublishers.ofString(body)) .build(); return httpClient.sendAsync(httpRequest, HttpResponse.BodyHandlers.ofString()).thenApply( r -> { ElasticsearchResponse<CollectionTag> elasticsearchResponse; try { if (r.body() != null) { elasticsearchResponse = objectMapper.readValue(r.body(), new TypeReference<>() { }); Hits<CollectionTag> hits = elasticsearchResponse.getHits(); if (hits != null && hits.getHits() != null) { return hits.getHits().stream().map(Hit::getT).collect(Collectors.toList()); //return new SearchResult(hits.getTotal().getValue(), illustrationList); } } } catch (IOException e) { e.printStackTrace(); } return null; } ); }
Example #24
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 #25
Source File: HaveIBeenPwned.java From passpol with Apache License 2.0 | 6 votes |
@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 #26
Source File: JdkHttpClientServiceShould.java From mutual-tls-ssl with Apache License 2.0 | 6 votes |
@Test @SuppressWarnings({"unchecked", "rawtypes"}) public void executeRequest() throws Exception { HttpResponse httpResponse = mock(HttpResponse.class); when(httpClient.send(any(HttpRequest.class), any(HttpResponse.BodyHandler.class))).thenReturn(httpResponse); when(httpResponse.statusCode()).thenReturn(200); when(httpResponse.body()).thenReturn("Hello"); ArgumentCaptor<HttpRequest> httpRequestArgumentCaptor = ArgumentCaptor.forClass(HttpRequest.class); ArgumentCaptor<HttpResponse.BodyHandler<String>> bodyHandlerArgumentCaptor = ArgumentCaptor.forClass(HttpResponse.BodyHandler.class); ClientResponse clientResponse = victim.executeRequest(HTTP_URL); assertThat(clientResponse.getStatusCode()).isEqualTo(200); assertThat(clientResponse.getResponseBody()).isEqualTo("Hello"); verify(httpClient, times(1)).send(httpRequestArgumentCaptor.capture(), bodyHandlerArgumentCaptor.capture()); assertThat(httpRequestArgumentCaptor.getValue().uri().toString()).isEqualTo(HTTP_URL); assertThat(httpRequestArgumentCaptor.getValue().method()).isEqualTo(GET_METHOD); assertThat(httpRequestArgumentCaptor.getValue().headers().map()).containsExactly(Assertions.entry(HEADER_KEY_CLIENT_TYPE, Collections.singletonList(JDK_HTTP_CLIENT.getValue()))); assertThat(bodyHandlerArgumentCaptor.getValue()).isEqualTo(HttpResponse.BodyHandlers.ofString()); }
Example #27
Source File: CommonService.java From Pixiv-Illustration-Collection-Backend with Apache License 2.0 | 5 votes |
public String getQQOpenId(String qqAccessToken) throws IOException, InterruptedException { HttpRequest build = HttpRequest.newBuilder() .uri(URI.create(QQ_BIND_URL_PRE + qqAccessToken)).GET() .build(); String body = httpClient.send(build, HttpResponse.BodyHandlers.ofString()).body(); if (body != null && body.contains("openid")) { int i = body.indexOf("\"openid\":\""); return body.substring(i + 10, i + 42); } throw new BusinessException(HttpStatus.BAD_REQUEST, "access_token不正确"); }
Example #28
Source File: AsyncOneRequest1.java From Java-Coding-Problems with MIT License | 5 votes |
public void triggerOneAyncRequest() throws IOException, InterruptedException, ExecutionException, TimeoutException { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://reqres.in/api/users/2")) .build(); client.sendAsync(request, HttpResponse.BodyHandlers.ofString()) .thenApply(HttpResponse::body) .exceptionally(e -> "Exception: " + e) .thenAccept(System.out::println) .get(30, TimeUnit.SECONDS); // or join() }
Example #29
Source File: FakeClassnameTags123Api.java From openapi-generator with Apache License 2.0 | 5 votes |
private HttpRequest.Builder testClassnameRequestBuilder(Client body) throws ApiException { // verify the required parameter 'body' is set if (body == null) { throw new ApiException(400, "Missing the required parameter 'body' when calling testClassname"); } HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); String localVarPath = "/fake_classname_test"; localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath)); localVarRequestBuilder.header("Content-Type", "application/json"); localVarRequestBuilder.header("Accept", "application/json"); try { byte[] localVarPostBody = memberVarObjectMapper.writeValueAsBytes(body); localVarRequestBuilder.method("PATCH", HttpRequest.BodyPublishers.ofByteArray(localVarPostBody)); } catch (IOException e) { throw new ApiException(e); } if (memberVarReadTimeout != null) { localVarRequestBuilder.timeout(memberVarReadTimeout); } if (memberVarInterceptor != null) { memberVarInterceptor.accept(localVarRequestBuilder); } return localVarRequestBuilder; }
Example #30
Source File: Main.java From Java-Coding-Problems with MIT License | 5 votes |
public static void main(String[] args) throws IOException, InterruptedException { HttpClient client = HttpClient.newBuilder() .followRedirects(HttpClient.Redirect.ALWAYS) .build(); 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()); }