Skip to content

Instantly share code, notes, and snippets.

@jsettlem
Created March 23, 2019 23:23
Show Gist options
  • Save jsettlem/f7774c8f70cb6b8df727364e9b5952af to your computer and use it in GitHub Desktop.
Save jsettlem/f7774c8f70cb6b8df727364e9b5952af to your computer and use it in GitHub Desktop.
package xyz.spookle.httpstreamtesting;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MimeType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.io.InputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.zip.Deflater;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
@RestController
@RequestMapping("/")
public class TestController {
@GetMapping("/test")
public ResponseEntity<InputStreamResource> wow() throws IOException {
URL url = new URL("https://speed.hetzner.de/100MB.bin");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
InputStream responseInputStream = con.getInputStream();
PipedOutputStream outputStream = new PipedOutputStream();
PipedInputStream inputStream = new PipedInputStream(outputStream);
new Thread(() -> {
byte[] buffer = new byte[1024];
int count;
try (ZipOutputStream zout = new ZipOutputStream(outputStream)) {
zout.setLevel(Deflater.NO_COMPRESSION);
zout.putNextEntry(new ZipEntry("test.html"));
while ((count = responseInputStream.read(buffer)) > 0) {
zout.write(buffer, 0, count);
}
} catch (IOException e) {
e.printStackTrace();
}
}).start();
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.asMediaType(MimeType.valueOf("application/zip")));
InputStreamResource isr = new InputStreamResource(inputStream);
return new ResponseEntity<>(isr, httpHeaders, HttpStatus.OK);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment