java 对 URL访问、校验端口是否占用、IP是否ping通

package cn.microvideo.info.service.impl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.xpath.XPathExpressionException;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.xml.sax.SAXException;

import cn.microvideo.info.domain.ServiceMonitorInfo;
import cn.microvideo.info.service.MonitorService;
import cn.microvideo.info.util.ServiceXMLUtil;

@Service("monitorService")
public class MonitorServiceImpl implements MonitorService {

	private Logger log = Logger.getLogger(MonitorServiceImpl.class);

	@Override
	public void execute() {
		ServiceXMLUtil serviceUtil = ServiceXMLUtil.getInstance();
		List<ServiceMonitorInfo> services = serviceUtil.getServices();
		for (ServiceMonitorInfo service : services) {
			monitoring(service);
		}
	}

	private void monitoring(ServiceMonitorInfo service) {
		String state = "监控服务获取失败";
		if (service != null) {
			boolean servResult = false;
			String url = service.getUrl();
			if (StringUtils.isNotBlank(url)) {
				String result = null;
				if ("post".equalsIgnoreCase(service.getMethod())) {
					try {
						result = postSend(url, service.getParam());
					} catch (Exception e) {
					}
					if (StringUtils.isNotBlank(result)) {
						servResult = true;
					}
				} else if ("get".equalsIgnoreCase(service.getMethod())) {
					try {
						result = sendGet(url, service.getParam());
					} catch (Exception e) {
					}
					if (StringUtils.isNotBlank(result)) {
						servResult = true;
					}
				}
				if (!servResult) {
					String regex = "//(.*?):(\\d+)/";
					Pattern p = Pattern.compile(regex);
					Matcher m = p.matcher(url);
					while (m.find()) {
						String location = m.group(1);
						try {
							Integer port = Integer.parseInt(m.group(2));
							servResult = validePort(location, port);
						} catch (Exception e) {
							servResult = false;
						}
						if (!servResult) {
							try {
								servResult = ping(location);
							} catch (Exception e) {
								servResult = false;
							}
							if(servResult){
								state = "服务器【IP】能够正常访问";
							}
						}else{
							state = "服务器【端口】能够正常访问";
						}

					}
				}else{
					state = "服务器【地址】能够正常访问";
				}
				if(!servResult){
					state = "服务器【地址、端口、IP】都无法访问";
				}
			}
		}
		service.setState(state);
		ServiceXMLUtil serviceUtil = ServiceXMLUtil.getInstance();
		try {
			serviceUtil.updateNodeById(service);
		} catch (XPathExpressionException e) {
			e.printStackTrace();
		} catch (TransformerException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private String postSend(String url, String param) {
		String result = null;
		PrintWriter out = null;
		BufferedReader in = null;
		try {
			URL realUrl = new URL(url);
			URLConnection conn = realUrl.openConnection();
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible;MSIE 6.0;Windows NT 5.1;SV1)");
			conn.setDoOutput(true);
			out = new PrintWriter(conn.getOutputStream());
			out.print(param);
			out.flush();
			in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			log.error("服务监控,发送POST请求异常:"+e.getMessage());
		} finally {
			try {
				if (out != null)
					out.close();
			} catch (Exception e2) {
			}
			try {
				if (in != null)
					in.close();
			} catch (Exception e2) {
			}
		}

		return result;
	}

	private String sendGet(String url, String param) {
		String result = "";
		BufferedReader in = null;
		try {
			String urlNameString = url + "?" + param;
			URL realUrl = new URL(urlNameString);
			URLConnection connection = realUrl.openConnection();
			connection.setRequestProperty("accept", "text/html, application/xhtml+xml, */*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("Accept-Encoding", "gzip, deflate");
			connection.setRequestProperty("Accept-Language", "zh-CN");
			connection.setRequestProperty("user-agent", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)");
			connection.connect();
			in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			log.error("服务监控,发送GET请求异常:"+e.getMessage());
		} finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e2) {
			}
		}
		return result;
	}

	/** 当返回值是true时,说明host是可用的,false则不可。*/
	public static boolean ping(String ipAddress) throws Exception {
		int timeOut = 3000; // 超时应该在3钞以上
		boolean status = InetAddress.getByName(ipAddress).isReachable(timeOut);
		return status;
	}

	private boolean validePort(String location, int port) {
		Socket s = new Socket();
		try {
			SocketAddress add = new InetSocketAddress(location, port);
			s.connect(add, 2000);
			return true;
		} catch (IOException e) {
			return false;
		}finally{
			try {
				s.close();
			} catch (IOException e1) {
			}
		}
	}

}
写道
此例结合上次XML解析文章

http://zhouhaiyang88.iteye.com/admin/blogs/2302442

 

猜你喜欢

转载自zhouhaiyang88.iteye.com/blog/2302568