URL url = new URL("http://example.com/api"); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setDoOutput(true); con.setChunkedStreamingMode(0); // enable chunked mode OutputStream out = con.getOutputStream(); for (int i = 0; i < 100; i++) { String data = "chunk " + i + "\n"; // create a chunk of data out.write(data.getBytes()); } out.close();
URL url = new URL("http://example.com/upload"); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setDoOutput(true); con.setChunkedStreamingMode(1024 * 1024); // send 1MB chunks OutputStream out = con.getOutputStream(); File file = new File("largefile.dat"); // assume a large file exists byte[] buffer = new byte[1024 * 1024]; try (InputStream in = new FileInputStream(file)) { int bytesRead; while ((bytesRead = in.read(buffer)) > 0) { out.write(buffer, 0, bytesRead); } } out.close();This example uploads a large file to a server in 1MB chunks. By setting the chunk size to 1MB, the client sends data in manageable chunks, which reduces memory usage and allows the server to process the data in a more efficient manner. In conclusion, the setChunkedStreamingMode method is part of the java.net package in Java and is used to enable chunked transfer encoding when sending data to an HTTP server. It is a useful technique for sending large amounts of data and provides greater control over the data being sent.