⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 httppoller.java

📁 高质量Java程序设计 源代码
💻 JAVA
字号:
package net.betterjava.design.sideeffect;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class HttpPoller {
	private final static String apacheCriteria = "apache";

	private static void log(Exception e) {
		e.printStackTrace(System.out);
	}

	private static void log(String msg) {
		System.out.println(msg);
	}

	private static void logResult(
		boolean success,
		HttpURLConnection httpConn,
		Exception e,
		String port) {
		//	httpConn and e can be null
		if (success)
			log("Poll server success " + port);
		else {
			log("Poll server fail");
		}

		if (e != null) {
			log(e);
		}
	}

	private static void poll(String port, String criteria) {
		URL url;
		URLConnection urlConn = null;
		HttpURLConnection httpConn = null;
		DataOutputStream printout;
		BufferedReader input = null;
		boolean success = false;
		boolean logFailure = false;

		log("");
		log("Poll http://" + port);
		log("Start:	" + (new Date(System.currentTimeMillis())));

		try {
			url = new URL("http://" + port);
			httpConn = (HttpURLConnection) url.openConnection();
			httpConn.setDoInput(true);
			httpConn.setDoOutput(true);
			httpConn.setUseCaches(false);
			httpConn.setRequestMethod("GET");

			log(
				"http status:"
					+ httpConn.getResponseCode()
					+ " "
					+ httpConn.getResponseMessage());

			input = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
			String str;
			while (null != ((str = input.readLine()))) {
				if (str.indexOf(criteria) != -1
					|| str.indexOf(criteria.toLowerCase()) != -1)
					success = true;
			}

			logResult(success, httpConn, null, port);
		} catch (Exception e) {
			success = false;
			logResult(success, httpConn, e, port);
		} finally {
			try {
				input.close();
			} catch (Exception e1) {
				log(e1);
			}
			httpConn.disconnect();
		}

		log("End: " + (new Date(System.currentTimeMillis())));
	}

	public static void main(String[] args) {
		log("Start poll process at " + (new Date(System.currentTimeMillis())));
		poll(args[0], apacheCriteria);
		log("End poll process at" + (new Date(System.currentTimeMillis())));
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -