判断网络是否链接

1. 这个方法我觉得最简单。(注意一定要到getInputStream这一步才能知道有没有连上,因为没联网时openConnection也不会抛异常)

public boolean hasNetConnection(){
		boolean b = false;
		InputStream in = null; 
		try {
			in = new URL("http://www.baidu.com").openConnection().getInputStream();
			b = true;
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally{
			if(in!=null)
			try {
				in.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return b;
	}



2. 本来想用dos 的 ping 命令,但是发现有没有联网都能返回InputStream,这样就要在返回的字符串中判断了:寻找里面有没有“TTL”关键字,拔了网线后会提示“ping 请求找不到主机” ,可是这是在windows系统下的方法,其他系统可能ping命令不同,或关键字不同,没试过。。所以还是第一种方法好。 各位还有没有更好的办法?
public boolean hasNetConnection(){
		boolean b = false;
		Scanner in = null; 
		try {
			Process process = Runtime.getRuntime().exec("ping www.baidu.com");
			in = new Scanner(process.getInputStream());
			CharSequence ttl = "TTL";
			while(in.hasNextLine()){
				if(in.nextLine().contains(ttl)){
					b = true;
					break;
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally{
			if(in!=null)
				in.close();
		}
		return b;
	}

你可能感兴趣的:(网络,url,链接,判断)