Java使用URL下载资源
示例代码:
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class GetURLResource {
public static void main(String[] args) throws Exception {
// 1. 下载地址
URL url = new URL("https://imgessl.kugou.com/stdmusic/20160907/20160907190359515842.jpg");
// 2. 使用http协议链接地址
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
// 3. 获取输入流
InputStream inputStream = urlConnection.getInputStream();
// 4. 创建输出流及buffer
FileOutputStream fileOutputStream = new FileOutputStream("test.jpg");
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, len);
}
// 5. 关闭流
fileOutputStream.close();
inputStream.close();
urlConnection.disconnect();
}
}
结果: