java 从url下载图片或者网页
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class URLDownloader extends Thread {
private String url;
private String filename;
@Override
public void run() {
try {
URL u = new URL(url);
HttpURLConnection connection = (HttpURLConnection) u.openConnection();
connection.setConnectTimeout(10000);
connection.setRequestMethod("GET");
connection.setDoInput(true);
if (connection.getResponseCode() != 404){
InputStream in = connection.getInputStream();
File myfile = new File(filename);
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(myfile));
byte[] buff = new byte[1024];
int read_size;
while((read_size = in.read(buff))>0){
out.write(buff,0,read_size);
}
in.close();
out.flush();
out.close();
connection.disconnect();
System.out.println("下载成功 "+myfile.getName());
}else {
System.out.println("连接失败!请检查url是否有问题");
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public URLDownloader(String url,String filename) {
super();
this.url = url;
this.filename = filename;
}
public static void main(String[] args) {
new URLDownloader("https://thirdwx.qlogo.cn/mmopen/vi_32/aUtjLpqvmObCZS5J9T5j7HcwcoHqLqibXGsvvhZZ6qbgeu0ibHW5fn34iaTxhv9NtYaOblT8uoric4p3LSlHmngUbw/132","1.png").start();
new URLDownloader("https://img2.baidu.com/it/u=1788336290,2322782865&fm=26&fmt=auto&gp=0.jpg","2.jpg").start();
}
}