主要用到的类
- 地址类: URL
- http类: HttpURLConnection
- 输入流: InputStream
- 输出流: FileOutputStream
上代码
package com.demo01;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Random;
public class TestURL {
public static void main(String[] args) throws Exception {
String downURL = "https://dss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=2771978851,2906984932&fm=26&gp=0.jpg";
URL url = new URL(downURL);
String fileName = "";
int index = url.getFile().lastIndexOf(".");
if (index != -1) {
fileName = url.getFile().substring(index);
}
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream is = urlConnection.getInputStream();
Random random = new Random();
FileOutputStream fos = new FileOutputStream("UrlDown" + random.nextInt(1000) + fileName);
byte[] buffer = new byte[1024];
int len;
while ((len = is.read(buffer)) != -1) {
fos.write(buffer,0,len);
}
fos.close();
is.close();
urlConnection.disconnect();
}
}