Java Code Examples for java.net.http.HttpClient#send()
The following examples show how to use
java.net.http.HttpClient#send() .
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: ViaAuthenticator.java From Java-Coding-Problems with MIT License | 7 votes |
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()); }
Example 2
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 3
Source File: ViaBody.java From Java-Coding-Problems with MIT License | 6 votes |
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()); }
Example 4
Source File: GitHub.java From jmbe with GNU General Public License v3.0 | 6 votes |
/** * Download the source code for a release to the specified directory * @param release to download * @param directory to store the downloaded zip file * @return path to the download zip file or null */ public static Path downloadReleaseSourceCode(Release release, Path directory) { HttpClient client = HttpClient.newBuilder() .followRedirects(HttpClient.Redirect.ALWAYS) .build(); System.out.println("Downloading: " + release.getDownloadUrl()); HttpRequest request = HttpRequest.newBuilder().uri(URI.create(release.getDownloadUrl())).build(); try { HttpResponse<Path> response = client.send(request, HttpResponse.BodyHandlers.ofFileDownload(directory, StandardOpenOption.CREATE, StandardOpenOption.WRITE)); System.out.println("Download Complete: HTTP Status " + response.statusCode()); return response.body(); } catch(Exception e) { System.out.println("Download Failed: Error downloading source code from GitHub - " + e.getLocalizedMessage()); e.printStackTrace(); } return null; }
Example 5
Source File: TelegramNotifier.java From blog-tutorials with MIT License | 6 votes |
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()); }
Example 6
Source File: HttpClientDemo.java From Learn-Java-12-Programming with MIT License | 6 votes |
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 7
Source File: HttpServerTest.java From piranha with BSD 3-Clause "New" or "Revised" License | 6 votes |
/** * 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: DefaultWebApplicationServerTest.java From piranha with BSD 3-Clause "New" or "Revised" License | 6 votes |
/** * Test process method. * * @throws Exception when a serious error occurs. */ @Test public void testProcess() throws Exception { DefaultWebApplicationServer server = new DefaultWebApplicationServer(); HttpServer httpServer = new DefaultHttpServer(8180, server, false); DefaultWebApplication application = new DefaultWebApplication(); application.setContextPath("/context"); application.addServlet("snoop", new TestSnoopServlet()); application.addServletMapping("snoop", "/snoop/*"); server.addWebApplication(application); server.initialize(); server.start(); httpServer.start(); try { HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder(new URI("http://localhost:8180/context/snoop/index.html")).build(); HttpResponse<Void> response = client.send(request, HttpResponse.BodyHandlers.discarding()); assertEquals(response.statusCode(), 200); } catch (IOException ioe) { throw new RuntimeException(ioe); } httpServer.stop(); server.stop(); }
Example 9
Source File: Main.java From Java-Coding-Problems with MIT License | 6 votes |
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 10
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() .proxy(ProxySelector.getDefault()) //.proxy(ProxySelector.of(new InetSocketAddress("proxy.host", 80))) .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()); }
Example 11
Source File: Example.java From java11-examples with MIT License | 5 votes |
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 12
Source File: MicroPiranhaIT.java From piranha with BSD 3-Clause "New" or "Revised" License | 5 votes |
/** * Test the Piranha Micro command line. * * @throws Exception when a serious error occurs. */ @Test @Disabled public void testCommandLine() throws Exception { String version = System.getProperty("VERSION"); ProcessBuilder builder = new ProcessBuilder(); builder.command("java", "-jar", "target/piranha-micro-" + version + "-all.jar"); Process process = builder.start(); HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder(new URI("http://localhost:8080/")).build(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); assertEquals(response.statusCode(), 404); process.destroyForcibly(); }
Example 13
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() .cookieHandler(new CookieManager(null, CookiePolicy.ACCEPT_NONE)) .build(); System.out.println(client.cookieHandler().orElseThrow()); */ CookieManager cm = new CookieManager(); cm.setCookiePolicy(CookiePolicy.ACCEPT_ALL); HttpClient client = HttpClient.newBuilder() .cookieHandler(cm) .build(); HttpRequest request = HttpRequest.newBuilder() .header("Authorization", "Bearer Q3ku4mp_hCQGvAFeYKa0ktFCDKS3VpSA1nwf") .uri(URI.create("https://gorest.co.in/public-api/users/1")) .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println("Status code: " + response.statusCode()); System.out.println("\n Body: " + response.body()); System.out.println("\nset-cookie header: " + response.headers().firstValue("set-cookie")); CookieStore cookieStore = cm.getCookieStore(); System.out.println("\nCookies: " + cookieStore.getCookies()); }
Example 14
Source File: Main.java From Java-Coding-Problems with MIT License | 5 votes |
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()); }
Example 15
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()); }
Example 16
Source File: Main.java From Java-Coding-Problems with MIT License | 4 votes |
public static void main(String[] args) throws IOException, InterruptedException { HttpClient client = HttpClient.newHttpClient(); // HTTP GET HttpRequest requestGet = HttpRequest.newBuilder() .GET() // can be omitted since it is default .uri(URI.create("https://reqres.in/api/users/2")) .build(); HttpResponse<String> responseGet = client.send( requestGet, HttpResponse.BodyHandlers.ofString()); System.out.println("GET | Status code: " + responseGet.statusCode()); System.out.println("GET | Body: " + responseGet.body()); System.out.println(); // HTTP POST HttpRequest requestPost = HttpRequest.newBuilder() .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString( "{\"name\": \"morpheus\",\"job\": \"leader\"}")) .uri(URI.create("https://reqres.in/api/users")) .build(); HttpResponse<String> responsePost = client.send( requestPost, HttpResponse.BodyHandlers.ofString()); System.out.println("POST | Status code: " + responsePost.statusCode()); System.out.println("POST | Body: " + responsePost.body()); System.out.println(); // HTTP PUT HttpRequest requestPut = HttpRequest.newBuilder() .header("Content-Type", "application/json") .PUT(HttpRequest.BodyPublishers.ofString( "{\"name\": \"morpheus\",\"job\": \"zion resident\"}")) .uri(URI.create("https://reqres.in/api/users/2")) .build(); HttpResponse<String> responsePut = client.send( requestPut, HttpResponse.BodyHandlers.ofString()); System.out.println("PUT | Status code: " + responsePut.statusCode()); System.out.println("PUT | Body: " + responsePut.body()); System.out.println(); // HTTP DELETE HttpRequest requestDelete = HttpRequest.newBuilder() .DELETE() .uri(URI.create("https://reqres.in/api/users/2")) .build(); HttpResponse<String> responseDelete = client.send( requestDelete, HttpResponse.BodyHandlers.ofString()); System.out.println("DELETE | Status code: " + responseDelete.statusCode()); System.out.println("DELETE | Body: " + responseDelete.body()); System.out.println(); // HTTP PATCH HttpRequest requestPatch = HttpRequest.newBuilder() .header("Content-Type", "application/json") .method("PATCH", HttpRequest.BodyPublishers.ofString( "{\"name\": \"morpheus\",\"job\": \"zion resident\"}")) .uri(URI.create("https://reqres.in/api/users/1")) .build(); HttpResponse<String> responsePatch = client.send( requestPatch, HttpResponse.BodyHandlers.ofString()); System.out.println("PATCH | Status code: " + responsePatch.statusCode()); System.out.println("PATCH | Body: " + responsePatch.body()); System.out.println(); // HTTP HEAD HttpRequest requestHead = HttpRequest.newBuilder() .method("HEAD", HttpRequest.BodyPublishers.noBody()) .uri(URI.create("https://reqres.in/api/users/1")) .build(); HttpResponse<String> responseHead = client.send( requestHead, HttpResponse.BodyHandlers.ofString()); System.out.println("HEAD | Status code: " + responseHead.statusCode()); System.out.println("HEAD | Body: " + responseHead.body()); }
Example 17
Source File: Main.java From Java-Coding-Problems with MIT License | 4 votes |
public static void main(String[] args) throws IOException, InterruptedException { Jsonb jsonb = JsonbBuilder.create(); HttpClient client = HttpClient.newHttpClient(); System.out.println("-------------------------------------"); System.out.println("-------------Get a user--------------"); System.out.println("-------------------------------------"); HttpRequest requestGet = HttpRequest.newBuilder() .uri(URI.create("https://reqres.in/api/users/2")) .build(); HttpResponse<User> responseGet = client.send(requestGet, JsonBodyHandler.jsonBodyHandler(jsonb, User.class)); System.out.println("Status code: " + responseGet.statusCode()); User user = responseGet.body(); System.out.println(user); System.out.println(); System.out.println("-------------------------------------"); System.out.println("-------------Update user-------------"); System.out.println("-------------------------------------"); user.getData().setEmail("[email protected]"); HttpRequest requestPut = HttpRequest.newBuilder() .header("Content-Type", "application/json") .uri(URI.create("https://reqres.in/api/users")) .PUT(HttpRequest.BodyPublishers.ofString(jsonb.toJson(user))) .build(); HttpResponse<User> responsePut = client.send( requestPut, JsonBodyHandler.jsonBodyHandler(jsonb, User.class)); System.out.println("Status code: " + responsePut.statusCode()); User updatedUser = responsePut.body(); System.out.println(updatedUser); System.out.println(); System.out.println("-------------------------------------"); System.out.println("-------------Post new user------------"); System.out.println("-------------------------------------"); Data data = new Data(); data.setId(10); data.setFirstName("John"); data.setLastName("Year"); data.setAvatar("https://johnyear.com/jy.png"); User newUser = new User(); newUser.setData(data); HttpRequest requestPost = HttpRequest.newBuilder() .header("Content-Type", "application/json") .uri(URI.create("https://reqres.in/api/users")) .POST(HttpRequest.BodyPublishers.ofString(jsonb.toJson(user))) .build(); HttpResponse<Void> responsePost = client.send( requestPost, HttpResponse.BodyHandlers.discarding()); System.out.println("Status code: " + responsePost.statusCode()); }
Example 18
Source File: Main.java From Java-Coding-Problems with MIT License | 4 votes |
public static void main(String[] args) throws IOException, InterruptedException { HttpClient client = HttpClient.newHttpClient(); // BodyPublishers.ofString() - create a String body HttpRequest requestBodyOfString = HttpRequest.newBuilder() .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString( "{\"name\": \"morpheus\",\"job\": \"leader\"}")) .uri(URI.create("https://reqres.in/api/users")) .build(); HttpResponse<String> responseBodyOfString = client.send( requestBodyOfString, HttpResponse.BodyHandlers.ofString()); System.out.println("BodyPublishers.ofString() | Status code: " + responseBodyOfString.statusCode()); System.out.println("BodyPublishers.ofString() | Body: " + responseBodyOfString.body()); System.out.println(); // BodyPublishers.ofInputStream() - create an input stream body HttpRequest requestBodyOfInputStream = HttpRequest.newBuilder() .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofInputStream(() -> inputStream("user.json"))) .uri(URI.create("https://reqres.in/api/users")) .build(); HttpResponse<String> responseBodyOfInputStream = client.send( requestBodyOfInputStream, HttpResponse.BodyHandlers.ofString()); System.out.println("BodyPublishers.ofInputStream() | Status code: " + responseBodyOfInputStream.statusCode()); System.out.println("BodyPublishers.ofInputStream() | Body: " + responseBodyOfInputStream.body()); System.out.println(); // BodyPublishers.ofByteArray() - create an byte array body HttpRequest requestBodyOfByteArray = HttpRequest.newBuilder() .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofByteArray(Files.readAllBytes(Path.of("user.json")))) .uri(URI.create("https://reqres.in/api/users")) .build(); HttpResponse<String> responseBodyOfByteArrays = client.send( requestBodyOfByteArray, HttpResponse.BodyHandlers.ofString()); System.out.println("BodyPublishers.ofByteArray() | Status code: " + responseBodyOfByteArrays.statusCode()); System.out.println("BodyPublishers.ofByteArray() | Body: " + responseBodyOfByteArrays.body()); System.out.println(); // BodyPublishers.ofFile() - create a body from a file HttpRequest requestBodyOfFile = HttpRequest.newBuilder() .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofFile(Path.of("user.json"))) .uri(URI.create("https://reqres.in/api/users")) .build(); HttpResponse<String> responseBodyOfFile = client.send( requestBodyOfFile, HttpResponse.BodyHandlers.ofString()); System.out.println("BodyPublishers.ofFile() | Status code: " + responseBodyOfFile.statusCode()); System.out.println("BodyPublishers.ofFile() | Body: " + responseBodyOfFile.body()); }
Example 19
Source File: Main.java From Java-Coding-Problems with MIT License | 4 votes |
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://central.maven.org/maven2/org/hibernate/hibernate-core/5.4.2.Final/hibernate-core-5.4.2.Final.jar")) .build(); HttpResponse<Path> response = client.send( request, HttpResponse.BodyHandlers.ofFile(Path.of("hibernate-core-5.4.2.Final.jar"))); System.out.println("Status code: " + response.statusCode()); System.out.println("\n Body: " + response.body()); }
Example 20
Source File: Main.java From Java-Coding-Problems with MIT License | 3 votes |
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, BodyHandlers.ofString()); System.out.println("Status code: " + response.statusCode()); System.out.println("\n Body: " + response.body()); }