HTTP协议----(2)Java程序检测HTTP服务是否打开

 1 package cn.koma;
 2 
 3 import java.io.BufferedReader;
 4 import java.io.IOException;
 5 import java.io.InputStreamReader;
 6 import java.io.OutputStream;
 7 import java.net.Socket;
 8 
 9 public class HttpServiceChecker
10 {
11     public static void main(String[] args) throws Exception
12     {
13         boolean flag = isHttpOpen("www.baidu.com"80);
14         System.out.println(flag ? "HTTP服务启动..." : "HTTP服务关闭...");
15     }
16     /**
17      * 判断ip的port端口是否开放了http服务
18      */
19     public static boolean isHttpOpen(String ip, int port)
20     {
21         if(isEmpty(ip))
22         {
23             return false;
24         }
25         Socket socket = null;        // socket链接
26         OutputStream os = null;      // 输出流
27         BufferedReader br = null;    // 输入流
28         boolean flag = false;        // 是否开启了HTTP服务
29         try
30         {
31             socket = new Socket(ip, port);
32             os = socket.getOutputStream();
33             br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
34             // 创建HTTP请求报文信息
35             String reqInfo =  "HEAD / HTTP/1.0"
36                             + "\r\n"
37                             + "Host: " + ip + ":" + port
38                             + "\r\n\r\n";
39             System.out.println("请求报文 : \r\n" + reqInfo);
40             // 发送请求消息
41             os.write(reqInfo.getBytes());
42             os.flush();
43             // 接收响应消息
44             String lineStr = null;
45             System.out.println("响应报文 : ");
46             while((lineStr = br.readLine()) != null)
47             {
48                 // 读取到了响应信息,表示该ip的port端口提供了HTTP服务
49                 System.out.println(lineStr);
50                 flag = true;
51             }
52         } catch (Exception e)
53         {
54             e.printStackTrace();
55         }
56         finally
57         {
58             try
59             {
60                 if(br != null)
61                     br.close();
62                 if(os != null)
63                     os.close();
64                 if(socket != null)
65                     socket.close();
66             } catch (IOException e)
67             {
68                 e.printStackTrace();
69             }
70         }
71         return flag;
72     }
73     
74     private static boolean isEmpty(String str)
75     {
76         if(str == null || str.length() <= 0 || str.trim() == null || str.trim().length() <= 0)
77         {
78             return true;
79         }
80         return false;
81     }
82 }

 

就是利用手工发送HTTP请求报文的原理,在程序中使用Socket方式发送请求报文。

posted on 2010-06-29 00:03  TroyZ  阅读(1569)  评论(0编辑  收藏  举报