HttpURLConnection下载文件

话不多说上代码:

直接粘贴即可使用!!!!

package com.yy;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class TestDemo3 {
	public static void main(String[] args) {
		HttpURLConnection conn = null;
		try {
			URL url = new URL("http://localhost:8080/jeecg-boot/sys/common/static/temp/asd.rar");//获得服务器的下载地址
			conn = (HttpURLConnection) url.openConnection();//打开连接
			conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");//设置字符集,格式
			conn.setRequestProperty("Connection", "close");//设置连接状态
			conn.setRequestMethod("GET");//设置请求方式
			conn.setDoOutput(true);//如果要使用URL连接进行输出,则标记为true
			conn.setRequestProperty("Authorization","token");//设置请求的token
			byte[] getData = readInputStream(conn.getInputStream());//把文件流放进字节数组里
			File file = new File("d:\\t\\asd.rar");//新建文件
			FileOutputStream fos = new FileOutputStream(file);//放人文件
			fos.write(getData);//把字节数组写进文件流中
		} catch (Exception ex) {
			ex.printStackTrace();
			String aa = ex.getMessage();
		} finally {
			if (conn != null) {
				conn.disconnect();
			}
		}

	}
	public static  byte[] readInputStream(InputStream inputStream) throws IOException {
		byte[] buffer = new byte[1024];
		int len = 0;
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		while((len = inputStream.read(buffer)) != -1) {
			bos.write(buffer, 0, len);
		}
		bos.close();
		return bos.toByteArray();
	}

}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值