C++,python,热爱算法和机器学习
全部博文(1214)
分类: 网络与安全
2012-05-02 22:13:53
最近做了个叫的网站,但是经常由于一些原因,会常常访问不到.我就想能不能写个程序使它检测到如果不能访问了就直接发邮件通知本人呢?借鉴HttpClient,我觉的可以实现了.呵呵.
HTTP 协议可能是现在 Internet 上使用得最多、最重要的协议了,越来越多的 Java 应用程序需要直接通过 HTTP
协议来访问网络资源。虽然在 JDK 的 java.net 包中已经提供了访问 HTTP 协议的基本功能,但是对于大部分应用程序来说,JDK
库本身提供的功能还不够丰富和灵活。HttpClient 是 Apache Jakarta Common
下的子项目,用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP
协议最新的版本和建议。HttpClient 已经应用在很多的项目中,比如 Apache Jakarta 上很著名的另外两个开源项目 Cactus
和 HTMLUnit 都使用了 HttpClient,更多使用 HttpClient 的应用可以参见。HttpClient 项目非常活跃,使用的人还是非常多的。目前 HttpClient 版本是在 2005.10.11 发布的 3.0 RC4
我写的代码:)
public Object[] getResponseInfo(String url,NameValuePair[] pairs,Cookie[] cookies,boolean isGet) {
Object[] arrResponse = new Object[3];
try {
if(pairs.length>1)
arrResponse[2] = pairs[0].getName() +"=" + pairs[0].getValue();
HttpClient client = new HttpClient(connectionManager);
HttpState initialState = new HttpState();
initialState.addCookies(cookies);
client.setState(initialState);
// 设置代理服务器地址和端口
// client.getHostConfiguration().setProxy("proxy_host_addr",proxy_port);
// 使用 GET 方法 ,如果服务器需要通过 HTTPS 连接,那只需要将下面 URL 中的 http 换成 https
//HttpMethod method = new GetMethod("");
// 使用POST方法
//client.
HttpMethod method = null;
if(isGet)
method = new GetMethod(url);
else
method = new PostMethod(url);
method.setQueryString(pairs);
client.executeMethod(method);
InputStream in = method.getResponseBodyAsStream();
Header[] headList = method.getResponseHeaders("Set-Cookie");
List<String> cooikeList = new ArrayList<String>();
for(Header head:headList){
logger.debug(head.getName()+"=" + head.getValue());
cooikeList.add(head.getValue());
}
arrResponse[0] = cooikeList;
byte[] streamBytes = XmlUtils.readStream2bytes(in);
arrResponse[1] = streamBytes;
if(logger.isDebugEnabled())
logger.debug(new String(streamBytes));
// 释放连接
method.releaseConnection();
return arrResponse;
} catch (Exception e) {
// TODO 自动生成 catch 块
e.printStackTrace();
return null;
}
}
public static MultiThreadedHttpConnectionManager connectionManager =
new MultiThreadedHttpConnectionManager();
有了这一招,对待的检测就没有问题了.