import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
public class Network {
private static boolean flag;
/**
* @param args
*/
public static void main(String[] args) {
download();
}
/**
* 测试网络下载速度(测试网络速度)
* @return 返回真表示网络连接正常 返回假表示网络连接异常或超时
*/
public synchronized static boolean download() {
flag = false;
//定义子线程 监控是否超时
new Thread(new Runnable() {
public void run() {
int times = 0;
while(true){
times++;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
//设置超时 5秒后超时跳出
if(times >= 50){
flag = true;
break;
}
}
}
}).start();
int bytesum = 0;
int byteread = 0;
URL url = null;
try {
/*
* 链接地址可以是任何可以访问的网络链接 用于下载文件 测试下载速度
* 如果下载文件内容大小太小 测试结果可能偏低
*/
url = new URL("https://mat1.gtimg.com/libs/jquery/1.12.0/jquery.min.js");
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
try {
URLConnection conn = url.openConnection();
InputStream inStream = conn.getInputStream();
byte[] buffer = new byte[1024];
System.out.println("开始时间:" + new Date().getTime());
long startTime = System.currentTimeMillis();
while ((byteread = inStream.read(buffer)) != -1) {
bytesum += byteread;
System.out.println(bytesum);
if(flag == true){
break;
}
}
if(flag == true){
System.out.println("下载超时!");
return false;
}
System.out.println("文件大小:" + (float)bytesum / 1024 + "Kb");
System.out.println("结束时间:" + new Date().getTime());
long endTime = System.currentTimeMillis();
System.out.println("耗时:" + String.valueOf((float)(endTime - startTime)/1000) + "秒");
float down_sd = bytesum/(endTime - startTime)*1000/1024;
System.out.println("下载速度:" + down_sd + "Kb");
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
}