类java.net.http.HttpClient源码实例Demo

下面列出了怎么用java.net.http.HttpClient的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: Java-Coding-Problems   文件: ViaBody.java
public void bodyExample() throws IOException, InterruptedException {
    
    HttpClient client = HttpClient.newHttpClient();

    HttpRequest request = HttpRequest.newBuilder()
            .header("Content-Type", "application/json")
            .POST(BodyPublishers.ofString(
                    "{\"email\":\"[email protected]\",\"password\":\"cityslicka\"}"))
            .uri(URI.create("https://reqres.in/api/login"))
            .build();

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

    System.out.println("Status code: " + response.statusCode());
    System.out.println("\n Body: " + response.body());
}
 
源代码2 项目: Java-Coding-Problems   文件: ViaAuthenticator.java
public void authenticatorExample() throws IOException, InterruptedException {

        HttpClient client = HttpClient.newBuilder()
                .authenticator(new Authenticator() {
                    @Override
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(
                                "username",
                                "password".toCharArray());
                    }
                }).build();

        HttpRequest request = HttpRequest.newBuilder()
                // ...           
                .build();

        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
    }
 
源代码3 项目: Java-Coding-Problems   文件: Main.java
public static void main(String[] args) throws IOException, InterruptedException {

        HttpClient client = HttpClient.newHttpClient();

        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://reqres.in/api/users/2"))
                .build();

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

        System.out.println("Version: " + response.version());
        System.out.println("\nURI: " + response.uri());
        System.out.println("\nStatus code: " + response.statusCode());
        System.out.println("\nHeaders: " + response.headers());
        System.out.println("\n Body: " + response.body());
    }
 
源代码4 项目: Java-Coding-Problems   文件: Main.java
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());
        });
    }
 
源代码5 项目: Java-Coding-Problems   文件: Main.java
public static void main(String[] args) throws IOException, InterruptedException {

        Map<Object, Object> data = new LinkedHashMap<>();
        data.put("author", "Lorem Ipsum Generator");
        data.put("filefield", Path.of("LoremIpsum.txt"));
        String boundary = UUID.randomUUID().toString().replaceAll("-", "");

        HttpClient client = HttpClient.newHttpClient();        
        
        HttpRequest request = HttpRequest.newBuilder()
                .header("Content-Type", "multipart/form-data;boundary=" + boundary)
                .POST(MultipartBodyPublisher.ofMultipart(data, boundary))
                .uri(URI.create("http://jkorpela.fi/cgi-bin/echoraw.cgi"))
                .build();

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

        System.out.println("Status code: " + response.statusCode());
        System.out.println("\n Body: " + response.body());
    }
 
源代码6 项目: demo-java-x   文件: Http2Api.java
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));
}
 
源代码7 项目: Java-Coding-Problems   文件: Main.java
public static void main(String[] args) throws IOException, InterruptedException {

        HttpClient client = HttpClient.newHttpClient();

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

        client.sendAsync(request, HttpResponse.BodyHandlers.ofString(), pushPromiseHandler())
                .thenApply(HttpResponse::body)
                .thenAccept((b) -> System.out.println("\nMain resource:\n" + b))
                .join();

        asyncPushRequests.forEach(CompletableFuture::join);

        System.out.println("\nFetched a total of " + asyncPushRequests.size() + " push requests");
    }
 
源代码8 项目: Java-Coding-Problems   文件: Main.java
public static void main(String[] args) throws IOException, InterruptedException {

        HttpClient client = HttpClient.newHttpClient();

        HttpRequest request = HttpRequest.newBuilder()
                .header("Accept-Encoding", "gzip")
                .uri(URI.create("https://davidwalsh.name"))
                .build();

        HttpResponse<InputStream> response = client.send(
                request, HttpResponse.BodyHandlers.ofInputStream());

        System.out.println("Status code: " + response.statusCode());

        String encoding = response.headers().firstValue("Content-Encoding").orElse("");
        System.out.println("\nEncoding: " + encoding + "\n");

        if ("gzip".equals(encoding)) {
            String gzipAsString = gzipToString(response.body());
            System.out.println(gzipAsString);
        } else {
            String isAsString = isToString(response.body());
            System.out.println(isAsString);
        }
    }
 
源代码9 项目: tutorials   文件: HttpClientUnitTest.java
@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));
}
 
源代码10 项目: piranha   文件: MicroPiranhaTest.java
/**
 * Test changing port.
 *
 * @throws Exception when an error occurs.
 */
@Test
@Disabled
public void testChangingPort() throws Exception {
    System.setProperty("java.naming.factory.initial", "cloud.piranha.jndi.memory.DefaultInitialContextFactory");
    final MicroPiranha piranha = new MicroPiranha();
    piranha.configure(new String[]{"--port", "8088"});
    Thread thread = new Thread(piranha);
    thread.start();
    Thread.sleep(3000);
    try {
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder(URI.create("http://localhost:8088/does-not-exist")).build();
        HttpResponse<Void> response = client.send(request, HttpResponse.BodyHandlers.discarding());
        assertEquals(response.statusCode(), 404);
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    }
    piranha.stop();
    Thread.sleep(3000);
}
 
源代码11 项目: tutorials   文件: HttpClientUnitTest.java
@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"));
}
 
源代码12 项目: tutorials   文件: HttpClientUnitTest.java
@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());
}
 
源代码13 项目: piranha   文件: HttpServerTest.java
/**
 * 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();
    }
}
 
源代码14 项目: piranha   文件: DefaultHttpServerTest.java
/**
 * 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();
    }
}
 
源代码15 项目: hellokoding-courses   文件: HttpClientExamples.java
@Test
public void postAsync() {
    HttpClient client = HttpClient.newHttpClient();

    HttpRequest request = HttpRequest.newBuilder()
        .uri(URI.create("http://localhost:8081/test/resource"))
        .header("Accept", "application/json")
        .POST(HttpRequest.BodyPublishers.ofString("ping!"))
        .build();

    CompletableFuture<HttpResponse<String>> completableFuture =
        client.sendAsync(request, HttpResponse.BodyHandlers.ofString());
    completableFuture
        .thenApplyAsync(HttpResponse::headers)
        .thenAcceptAsync(System.out::println);
    HttpResponse<String> response = completableFuture.join();

    assertThat(response.statusCode()).isEqualTo(200);
}
 
源代码16 项目: hellokoding-courses   文件: HttpClientExamples.java
@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);
}
 
源代码17 项目: hellokoding-courses   文件: HttpClientExamples.java
@Test
public void basicAuthentication() throws IOException, InterruptedException {
    HttpClient client = HttpClient.newHttpClient();

    String encodedAuth = Base64.getEncoder()
        .encodeToString(("user" + ":" + "pass").getBytes(StandardCharsets.UTF_8));

    HttpRequest request = HttpRequest.newBuilder()
        .uri(URI.create("http://localhost:8081/test/secure"))
        .header("Authorization", "Basic " + encodedAuth)
        .build();

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

    assertThat(response.statusCode()).isEqualTo(200);
}
 
源代码18 项目: jmbe   文件: GitHub.java
/**
 * 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;
}
 
源代码19 项目: piranha   文件: DefaultWebApplicationServerTest.java
/**
 * 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();
}
 
源代码20 项目: openapi-generator   文件: ApiClient.java
/**
 * Ctor.
 */
public ApiClient() {
  builder = HttpClient.newBuilder();
  mapper = new ObjectMapper();
  mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
  mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
  mapper.configure(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE, false);
  mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
  mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
  mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
  mapper.registerModule(new JavaTimeModule());
  JsonNullableModule jnm = new JsonNullableModule();
  mapper.registerModule(jnm);
  URI baseURI = URI.create("http://petstore.swagger.io:80/v2");
  scheme = baseURI.getScheme();
  host = baseURI.getHost();
  port = baseURI.getPort();
  basePath = baseURI.getRawPath();
  interceptor = null;
  readTimeout = null;
  responseInterceptor = null;
}
 
源代码21 项目: piranha   文件: MicroPiranhaTest.java
/**
 * 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);
}
 
源代码22 项目: piranha   文件: HttpServerTest.java
/**
 * 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();
    }
}
 
源代码23 项目: teku   文件: ExternalMessageSignerService.java
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);
      });
}
 
源代码24 项目: java11-examples   文件: Example.java
public static void asyncGet(String uri) throws Exception {
    HttpClient client = HttpClient.newHttpClient();
    HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create(uri))
            .build();

    CompletableFuture<HttpResponse<String>> responseCompletableFuture = client.sendAsync(request, HttpResponse.BodyHandlers.ofString());
    responseCompletableFuture.whenComplete((resp, t) -> {
        if (t != null) {
            t.printStackTrace();
        } else {
            System.out.println(resp.body());
            System.out.println(resp.statusCode());
        }
    }).join();
}
 
源代码25 项目: mangooio   文件: WebSocketControllerTest.java
@Test
public void testWebSocketConnection() throws Exception {
    // given
    final HttpClient httpClient = HttpClient.newHttpClient();
    final Config config = Application.getInstance(Config.class);
    final String uri = "ws://" + config.getConnectorHttpHost() + ":" + config.getConnectorHttpPort() + "/websocket";

    // when
    Listener listener = new Listener() {
        @Override
        public void onOpen(WebSocket webSocket) {
            connected = true;
        }
    };
    httpClient.newWebSocketBuilder().buildAsync(new URI(uri), listener).join();
    
    // then
    assertThat(connected, equalTo(true));
}
 
源代码26 项目: Learn-Java-12-Programming   文件: HttpClientDemo.java
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...");
    }
 
源代码27 项目: Learn-Java-12-Programming   文件: HttpClientDemo.java
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...");
}
 
源代码28 项目: blog-tutorials   文件: TelegramNotifier.java
public static void main(String[] args) throws IOException, InterruptedException {

        String message = "Hello World from Java 11";

        HttpClient client = HttpClient.newBuilder()
                .connectTimeout(Duration.ofSeconds(5))
                .version(HttpClient.Version.HTTP_2)
                .build();

        UriBuilder builder = UriBuilder
                .fromUri("https://api.telegram.org")
                .path("/{token}/sendMessage")
                .queryParam("chat_id", CHAT_ID)
                .queryParam("text", message);

        HttpRequest request = HttpRequest.newBuilder()
                .GET()
                .uri(builder.build("bot" + TOKEN))
                .timeout(Duration.ofSeconds(5))
                .build();

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

        System.out.println(response.statusCode());
        System.out.println(response.body());
    }
 
源代码29 项目: tutorials   文件: HttpClientUnitTest.java
@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"));
    }

}
 
源代码30 项目: tutorials   文件: HttpClientExample.java
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);
}
 
 类所在包
 同包方法