2018-08-08 17:14:18 +08:00

60 lines
1.9 KiB
Java

package com.tenwa.app.invoice.utils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
import java.io.*;
import java.net.URI;
public class DownloadPdfUtil {
public static void go(String url,String localUrl) throws Exception {
RestTemplate restTemplate = new RestTemplate();
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
URI uri = builder.build(true).toUri();
String filePath = localUrl ;
File file = new File(filePath);
File parentFile = file.getParentFile();
if(!parentFile.exists()){
parentFile.mkdirs();
}
InputStream inputStream = null;
OutputStream outputStream = null;
try {
HttpHeaders headers = new HttpHeaders();
ResponseEntity<byte[]> response = restTemplate.exchange(uri, HttpMethod.GET, new HttpEntity<byte[]>(headers), byte[].class);
byte[] result = response.getBody();
inputStream = new ByteArrayInputStream(result);
outputStream = new FileOutputStream(new File(filePath));
int len = 0;
byte[] buf = new byte[1024];
while ((len = inputStream.read(buf, 0, 1024)) != -1) {
outputStream.write(buf, 0, len);
}
outputStream.flush();
} catch (Exception e) {
e.printStackTrace();
throw new Exception(e);
} finally {
try {
if (inputStream != null) inputStream.close();
if (outputStream != null) outputStream.close();
} catch (IOException e) {
e.printStackTrace();
throw new IOException(e);
}
}
}
}