使用HttpURLConnection进行简单的网络下载,URL资源定位可以从网络上进行复制,openConnection打开网络链接,设置一些请求头,然后通过数据流的方式进行下载。话不多说,直接上代码,亲测可用。
public class httpConnection {
static URL url ;
static long fileSize;
public static void main(String []args){
try {
url = new URL("http://mirror.bit.edu.cn/apache/tomcat/tomcat-7/v7.0.90/bin/apache-tomcat-7.0.90.zip");
HttpURLConnection connection = getConnection();
if(connection.getResponseCode() == 200){
System.out.println("200 Response");
fileSize = connection.getContentLengthLong();
System.out.println("200 Response size:"+fileSize);
System.out.println("200 Response size:"+fileSize/1024/1024);
System.out.println("200 Response size:"+connection.getHeaderField("Content-Disposition"));
downloadFile(connection.getInputStream());
}else {
System.err.println("Not 200 Response"+connection.getResponseCode());
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void downloadFile(InputStream inputStream) throws IOException {
DataInputStream dataInputStream = new DataInputStream(inputStream);
File file = new File("C:\\Users\\Administrator\\Desktop\\tmp\\tmp.zip");
if(!file.exists()){
file.createNewFile();
}
FileOutputStream out = new FileOutputStream(file);
byte []bytes = new byte[1024];
int bit;
while ((bit = dataInputStream.read(bytes))!= -1){
out.write(bytes,0,bit);
}
out.flush();
out.close();
inputStream.close();
}
public static HttpURLConnection getConnection() throws IOException {
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(20000);
connection.setReadTimeout(20000);
connection.setRequestProperty("Accept-Charset", "UTF-8");
connection.setRequestProperty("contentType", "UTF-8");
connection.setRequestMethod("GET");
return connection;
}
}