通过文件下载地址,获取到文件流
/* 根据地址获得数据的输入流 */
String fileUrl = ossEndpoint + (ossEndpoint.endsWith("/") ? "" : "/") + relativelyLink;
HttpURLConnection conn = null;
// 文件流
ByteArrayInputStream inputStream = null;
try {
URL url = new URL(fileUrl);
conn = (HttpURLConnection) url.openConnection();
// conn.setRequestMethod("GET");
// conn.setConnectTimeout(20 * 1000);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
IOUtils.copy(conn.getInputStream(), outputStream);
inputStream = new ByteArrayInputStream(outputStream.toByteArray());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != conn) {
conn.disconnect();
}
}
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* NetUtils class.
*
* @author J.Wong
* @date 2022/06/01
*/
@Component
public class NetUtils {
private static final Logger log = LoggerFactory.getLogger(NetUtils.class);
private static final String ENTITY_NAME = "netUtils";
private static NetUtils netUtils;
public NetUtils() {
log.info("init NetUtils");
netUtils = this;
}
/**
* getInstance.
*
* @return {@link NetUtils}
*/
public static NetUtils getInstance() {
log.info("return NetUtils");
return NetUtils.netUtils;
}
/**
* 根据地址获得数据的输入流
*
* @param fileUrl 网络连接地址
* @return url的输入流
*/
public ByteArrayInputStream getInputStreamByUrl(String fileUrl) {
/* 根据地址获得数据的输入流 */
HttpURLConnection conn = null;
// 文件流
ByteArrayInputStream inputStream = null;
try {
URL url = new URL(fileUrl);
conn = (HttpURLConnection) url.openConnection();
// conn.setRequestMethod("GET");
// conn.setConnectTimeout(20 * 1000);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
IOUtils.copy(conn.getInputStream(), outputStream);
inputStream = new ByteArrayInputStream(outputStream.toByteArray());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != conn) {
conn.disconnect();
}
}
return inputStream;
}
}