JAVA通过HttpURLConnection 上传和下载文件的方法
发布时间 - 2026-01-11 03:25:05 点击率:次本文介绍了JAVA通过HttpURLConnection 上传和下载文件的方法,分享给大家,具体如下:

HttpURLConnection文件上传
HttpURLConnection采用模拟浏览器上传的数据格式,上传给服务器
上传代码如下:
package com.util;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;
import java.util.Map;
/**
* Java原生的API可用于发送HTTP请求,即java.net.URL、java.net.URLConnection,这些API很好用、很常用,
* 但不够简便;
*
* 1.通过统一资源定位器(java.net.URL)获取连接器(java.net.URLConnection) 2.设置请求的参数 3.发送请求
* 4.以输入流的形式获取返回内容 5.关闭输入流
*
* @author H__D
*
*/
public class HttpConnectionUtil {
/**
* 多文件上传的方法
*
* @param actionUrl:上传的路径
* @param uploadFilePaths:需要上传的文件路径,数组
* @return
*/
@SuppressWarnings("finally")
public static String uploadFile(String actionUrl, String[] uploadFilePaths) {
String end = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
DataOutputStream ds = null;
InputStream inputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader reader = null;
StringBuffer resultBuffer = new StringBuffer();
String tempLine = null;
try {
// 统一资源
URL url = new URL(actionUrl);
// 连接类的父类,抽象类
URLConnection urlConnection = url.openConnection();
// http的连接类
HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
// 设置是否从httpUrlConnection读入,默认情况下是true;
httpURLConnection.setDoInput(true);
// 设置是否向httpUrlConnection输出
httpURLConnection.setDoOutput(true);
// Post 请求不能使用缓存
httpURLConnection.setUseCaches(false);
// 设定请求的方法,默认是GET
httpURLConnection.setRequestMethod("POST");
// 设置字符编码连接参数
httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
// 设置字符编码
httpURLConnection.setRequestProperty("Charset", "UTF-8");
// 设置请求内容类型
httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
// 设置DataOutputStream
ds = new DataOutputStream(httpURLConnection.getOutputStream());
for (int i = 0; i < uploadFilePaths.length; i++) {
String uploadFile = uploadFilePaths[i];
String filename = uploadFile.substring(uploadFile.lastIndexOf("//") + 1);
ds.writeBytes(twoHyphens + boundary + end);
ds.writeBytes("Content-Disposition: form-data; " + "name=\"file" + i + "\";filename=\"" + filename
+ "\"" + end);
ds.writeBytes(end);
FileInputStream fStream = new FileInputStream(uploadFile);
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int length = -1;
while ((length = fStream.read(buffer)) != -1) {
ds.write(buffer, 0, length);
}
ds.writeBytes(end);
/* close streams */
fStream.close();
}
ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
/* close streams */
ds.flush();
if (httpURLConnection.getResponseCode() >= 300) {
throw new Exception(
"HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
}
if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
inputStream = httpURLConnection.getInputStream();
inputStreamReader = new InputStreamReader(inputStream);
reader = new BufferedReader(inputStreamReader);
tempLine = null;
resultBuffer = new StringBuffer();
while ((tempLine = reader.readLine()) != null) {
resultBuffer.append(tempLine);
resultBuffer.append("\n");
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (ds != null) {
try {
ds.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (inputStreamReader != null) {
try {
inputStreamReader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return resultBuffer.toString();
}
}
public static void main(String[] args) {
// 上传文件测试
String str = uploadFile("http://127.0.0.1:8080/image/image.do",new String[] { "/Users//H__D/Desktop//1.png","//Users/H__D/Desktop/2.png" });
System.out.println(str);
}
}
HttpURLConnection文件下载
下载代码如下:
package com.util;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;
import java.util.Map;
/**
* Java原生的API可用于发送HTTP请求,即java.net.URL、java.net.URLConnection,这些API很好用、很常用,
* 但不够简便;
*
* 1.通过统一资源定位器(java.net.URL)获取连接器(java.net.URLConnection) 2.设置请求的参数 3.发送请求
* 4.以输入流的形式获取返回内容 5.关闭输入流
*
* @author H__D
*
*/
public class HttpConnectionUtil {
/**
*
* @param urlPath
* 下载路径
* @param downloadDir
* 下载存放目录
* @return 返回下载文件
*/
public static File downloadFile(String urlPath, String downloadDir) {
File file = null;
try {
// 统一资源
URL url = new URL(urlPath);
// 连接类的父类,抽象类
URLConnection urlConnection = url.openConnection();
// http的连接类
HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
// 设定请求的方法,默认是GET
httpURLConnection.setRequestMethod("POST");
// 设置字符编码
httpURLConnection.setRequestProperty("Charset", "UTF-8");
// 打开到此 URL 引用的资源的通信链接(如果尚未建立这样的连接)。
httpURLConnection.connect();
// 文件大小
int fileLength = httpURLConnection.getContentLength();
// 文件名
String filePathUrl = httpURLConnection.getURL().getFile();
String fileFullName = filePathUrl.substring(filePathUrl.lastIndexOf(File.separatorChar) + 1);
System.out.println("file length---->" + fileLength);
URLConnection con = url.openConnection();
BufferedInputStream bin = new BufferedInputStream(httpURLConnection.getInputStream());
String path = downloadDir + File.separatorChar + fileFullName;
file = new File(path);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
OutputStream out = new FileOutputStream(file);
int size = 0;
int len = 0;
byte[] buf = new byte[1024];
while ((size = bin.read(buf)) != -1) {
len += size;
out.write(buf, 0, size);
// 打印下载百分比
// System.out.println("下载了-------> " + len * 100 / fileLength +
// "%\n");
}
bin.close();
out.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
return file;
}
}
public static void main(String[] args) {
// 下载文件测试
downloadFile("http://localhost:8080/images/1467523487190.png", "/Users/H__D/Desktop");
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
# java文件上传和下载
# java文件上传下载
# JAVA
# HttpURLConnection
# 上传
# 下载
# Java HttpURLConnection使用方法与实例演示分析
# 浅谈Java HttpURLConnection请求方式
# 一文读懂JAVA中HttpURLConnection的用法
# Java HttpURLConnection使用方法详解
# java HttpURLConnection类的disconnect方法与http长连接详解
# 定位器
# 很好用
# 文件上传
# 可用于
# 抽象类
# 给大家
# 到此
# 大家多多
# 上传文件
# 情况下
# 数据格式
# param
# twoHyphens
# boundary
# null
# inputStream
# ds
# inputStreamReader
# HttpConnectionUtil
相关栏目:
【
网站优化151355 】
【
网络推广146373 】
【
网络技术251813 】
【
AI营销90571 】
相关推荐:
Windows家庭版如何开启组策略(gpedit.msc)?(安装方法)
香港服务器网站推广:SEO优化与外贸独立站搭建策略
HTML 中动态设置元素 name 属性的正确语法详解
Windows10电脑怎么查看硬盘通电时间_Win10使用工具检测磁盘健康
如何在万网主机上快速搭建网站?
小米17系列还有一款新机?主打6.9英寸大直屏和旗舰级影像
如何快速生成橙子建站落地页链接?
nodejs redis 发布订阅机制封装实现方法及实例代码
Laravel怎么处理异常_Laravel自定义异常处理与错误页面教程
EditPlus中的正则表达式 实战(4)
Laravel怎么集成Log日志记录_Laravel单文件与每日日志配置及自定义通道【详解】
Laravel如何使用Socialite实现第三方登录?(微信/GitHub示例)
网站制作报价单模板图片,小松挖机官方网站报价?
如何快速辨别茅台真假?关键步骤解析
Laravel数据库迁移怎么用_Laravel Migration管理数据库结构的正确姿势
html5怎么画眼睛_HT5用Canvas或SVG画眼球瞳孔加JS控制动态【绘制】
历史网站制作软件,华为如何找回被删除的网站?
WordPress 子目录安装中正确处理脚本路径的完整指南
如何生成腾讯云建站专用兑换码?
如何用低价快速搭建高质量网站?
Python函数文档自动校验_规范解析【教程】
音乐网站服务器如何优化API响应速度?
如何快速打造个性化非模板自助建站?
Laravel如何使用Gate和Policy进行授权?(权限控制)
开心动漫网站制作软件下载,十分开心动画为何停播?
清除minerd进程的简单方法
Laravel怎么进行数据库回滚_Laravel Migration数据库版本控制与回滚操作
网站图片在线制作软件,怎么在图片上做链接?
网易LOFTER官网链接 老福特网页版登录地址
php485函数参数是什么意思_php485各参数详细说明【介绍】
如何在Ubuntu系统下快速搭建WordPress个人网站?
详解MySQL数据库的安装与密码配置
儿童网站界面设计图片,中国少年儿童教育网站-怎么去注册?
uc浏览器二维码扫描入口_uc浏览器扫码功能使用地址
如何选择PHP开源工具快速搭建网站?
详解免费开源的.NET多类型文件解压缩组件SharpZipLib(.NET组件介绍之七)
Laravel策略(Policy)如何控制权限_Laravel Gates与Policies实现用户授权
北京专业网站制作设计师招聘,北京白云观官方网站?
Laravel如何配置和使用缓存?(Redis代码示例)
Python数据仓库与ETL构建实战_Airflow调度流程详解
详解阿里云nginx服务器多站点的配置
Laravel如何发送系统通知_Laravel Notifications实现多渠道消息通知
Laravel中的Facade(门面)到底是什么原理
Laravel怎么集成Vue.js_Laravel Mix配置Vue开发环境
Laravel如何发送邮件和通知_Laravel邮件与通知系统发送步骤
Laravel如何处理和验证JSON类型的数据库字段
瓜子二手车官方网站在线入口 瓜子二手车网页版官网通道入口
javascript日期怎么处理_如何格式化输出
VIVO手机上del键无效OnKeyListener不响应的原因及解决方法
如何实现建站之星域名转发设置?

