前言
由于业务场景的需要,上游系统需要给我们下游提供一个文件,这个文件上游包装成了一个Http的Get请求接口,这时灵光一现,可以使用java.net.URL下的方法来帮助我们来实现这个功能(当然使用org.apache.http.client.methods下的类也能解决,我们找个时间再说,这边文章主要帮助各位搬砖人了解java.net.URL的基本使用)
通用代码
package com.test;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import javax.servlet.http.HttpServletResponse;
public class fileDownloadTest {
public static void main(String[] args) throws MalformedURLException {
downloadNet("http://api.xxx.com/api/report/getfile?filecode=aa08690e60b8ce025a6813dad8ehu65e440");
}
public static void downloadNet(String path) throws MalformedURLException {
// 下载网络文件
int bytesum = 0;
int byteread = 0;
URL url = new URL(path);
try {
URLConnection conn = url.openConnection();
InputStream inStream = conn.getInputStream();
FileOutputStream fs = new FileOutputStream("K:\\dataExp\\test.pdf");
byte[] buffer = new byte[1204];
while ((byteread = inStream.read(buffer)) != -1) {
bytesum += byteread;
fs.write(buffer, 0, byteread);
}
fs.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
代码解读:本质上其实就是将上游返回的字节流转换为我们的文件,一定要确认好上游返回的文件类型,否则可能会出问题
特殊处理1:配置代理
//初始化代理
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("xx.xx.xx.x", 8099));
//初始化远程连接时加入进去就可以
URLConnection conn = url.openConnection(proxy);
特殊处理2:设置请求头(header)
//例如我们的场景需要在请求头加入类似token的验证值,使用URLConnection 的 setRequestProperty()即可
URLConnection conn = url.openConnection();
conn.setRequestProperty("Authorization", "Basic " + token);