Java中如何使用HttpURLConnection下载文件呢?
下文笔者讲述借助HttpURLConnection下载文件的方法及示例分享,如下所示
实现思路: 1.定义URL对象 2.使用url对象中的openConnection()方法,返回HttpURLConnection对象 3.使用httpurlConnection对象的getInputStream()方法即可获取相应的文件流 4.将文件流转换为相应的文件,并存储到硬盘上例
package com.java265;
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 TestClass {
public static void main(String[] args) {
HttpURLConnection conn = null;
try {
URL url = new URL("http://localhost:8080/test.jpg");//获得服务器的下载地址
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:\\test.jpg");//新建文件
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();
}
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


