通过JAVA提供的URL下载网络资源
package xyz.justgzx.test;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import org.junit.Test;
public class URLtest {
@Test
public void download() {
HttpsURLConnection connection = null;
InputStream is = null;
FileOutputStream fos = null;
String src1="https://t7.baidu.com/it/u=3034799576,2420598506&fm=193&f=GIF";
try {
URL url=new URL(src1);
connection = (HttpsURLConnection) url.openConnection();
connection.connect();
is = connection.getInputStream();
fos = new FileOutputStream(new File("star2.jpg"));
byte[] buf=new byte[1024*10];
int len;
while ((len=is.read(buf))!=-1) {
fos.write(buf, 0, len);
System.out.println("downloading.......");
}
System.out.println("下载完成");
} catch (IOException e) {
e.printStackTrace();
}finally {
if (fos!=null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (is!=null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (connection!=null) {
connection.disconnect();
}
}
}
}