package util;import constant.Constant;import javax.swing.*;import java.io.BufferedInputStream;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStream;import java.net.HttpURLConnection;import java.net.ProtocolException;import java.net.URL;import java.net.URLConnection;public class HttpDownloadUtil {/*** Java原生的API可用于发送HTTP请求,即java.net.URL、java.net.URLConnection,这些API很好用、很常用,* 但不够简便;** 1.通过统一资源定位器(java.net.URL)获取连接器(java.net.URLConnection) 2.设置请求的参数 3.发送请求* 4.以输入流的形式获取返回内容 5.关闭输入流** @author H__D**//*** @param urlPath 下载路径* @param downloadDir 下载存放目录* @return 返回下载文件*/public static File downloadFile(String urlPath, String downloadDir) throws Exception {File file = null;BufferedInputStream bin = null;OutputStream out = null;try {// 统一资源URL url = new URL(urlPath);// 连接类的父类,抽象类URLConnection urlConnection = url.openConnection();// http的连接类HttpURLConnection httpUrlConnection = (HttpURLConnection) urlConnection;// 设定请求的方法,默认是GEThttpUrlConnection.setRequestMethod("GET");httpUrlConnection.setConnectTimeout(60000);httpUrlConnection.setReadTimeout(60000);// 设置字符编码httpUrlConnection.setRequestProperty("Charset", "UTF-8");// 打开到此 URL 引用的资源的通信链接(如果尚未建立这样的连接)。httpUrlConnection.connect();// 文件名String filePathUrl = httpUrlConnection.getURL().getFile();String fileFullName = filePathUrl.substring(filePathUrl.lastIndexOf("/") + 1);bin = new BufferedInputStream(httpUrlConnection.getInputStream());// String path = downloadDir + File.separatorChar + fileFullName;String path = downloadDir + fileFullName;file = new File(path);if (!file.getParentFile().exists()) {file.getParentFile().mkdirs();}out = new FileOutputStream(file);int size;byte[] buf = new byte[2048];while ((size = bin.read(buf)) != -1) {out.write(buf, 0, size);}out.flush();} finally {if (bin != null) {try {bin.close();} catch (IOException ignored) {}}if (out != null) {try {out.close();} catch (IOException ignored) {}}}return file;}/** public static void main(String[] args) {** // 下载文件测试 downloadFile("http://localhost:8080/codeManZip/zip/coreCode.zip",* Constant.coreCode);** }*/}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。
1. 开源生态
2. 协作、人、软件
3. 评估模型