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

📄 httptest.java

📁 一个简单的HTTP服务器和HTTP客户端程序 HTTP客户端(即浏览器)只支持显示标准HTML
💻 JAVA
字号:
package web.http.test;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.Socket;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.Properties;

public class HTTPTest
{
    protected Socket client;

    protected BufferedOutputStream sender;

    protected BufferedInputStream receiver;

    protected URL target;

    private int responseCode = -1;

    private String responseMessage = "";

    private String serverVersion = "";

    private String content =null;
    
    private Properties header = new Properties();

    public HTTPTest()
    {
    }

    public HTTPTest(String url)
    {
        GET(url);
    }

    /* 
     * GET方法请求文件,图片,音频,视频等服务器资源
     */
    public void GET(String url)
    {
        try
        {
            checkHTTP(url);
            openServer(target.getHost(), target.getPort());
            String cmd = "GET "+target.getFile()+" HTTP/1.1\r\n"+ getBaseHeads() + "\r\n";
            sendMessage(cmd);
            receiveMessage();
        } catch (ProtocolException p)
        {
            p.printStackTrace();
            return;
        } catch (UnknownHostException e)
        {
            e.printStackTrace();
            return;
        } catch (IOException i)
        {
            i.printStackTrace();
            return;
        }
    }

    protected void checkHTTP(String url) throws ProtocolException
    {
        try
        {
            URL target = new URL(url);
            if (target == null
                    || !target.getProtocol().toUpperCase().equals("HTTP"))
                throw new ProtocolException("这不是HTTP协议");
            System.out.println("host:"+target.getHost()+"  File:"+target.getFile());
            this.target = target;
        } catch (MalformedURLException m)
        {
            throw new ProtocolException("协议格式错误");
        }
    }

    /*
     * 与Web服务器连接。若找不到Web服务器,InetAddress会引发UnknownHostException
     * 异常。若Socket连接失败,会引发IOException异常。
     */
    protected void openServer(String host, int port)
            throws UnknownHostException, IOException
    {
        header.clear();
        responseMessage = "";
        responseCode = -1;
        try
        {
            if (client != null)
            {
                closeServer();
            }
            InetAddress address = InetAddress.getByName(host);
            client = new Socket(address, port == -1 ? 80 : port);
            sender = new BufferedOutputStream(client.getOutputStream());
            receiver = new BufferedInputStream(client.getInputStream());
        } catch (UnknownHostException ukhe)
        {
            throw ukhe;
        } catch (IOException ioe)
        {
            throw ioe;
        }
    }

    /*
     * 关闭连接 
     * 同时关闭数据流
     */
    protected void closeServer() throws IOException
    {
        if (client == null)
            return;
        try
        {
            client.close();
            sender.close();
            receiver.close();
        } catch (IOException ioe)
        {
            throw ioe;
        }
        client = null;
        sender = null;
        receiver = null;
    }

    protected String getURLFormat(URL target)
    {
        String spec = "http://" + target.getHost();
        if (target.getPort() != -1)
            spec += ":" + target.getPort();
        return spec += target.getFile();
    }

    /* 
     * 发送数据 
     */
    protected void sendMessage(String data) throws IOException
    {
        System.out.println("发送给服务器数据:\n"+data.toString());
        sender.write(data.getBytes(), 0, data.length());
        sender.flush();
    }

    /* 
     * 接收来自HTTP服务器的数据
     * 并进行HTTP协议的解析
     */
    protected void receiveMessage() throws IOException
    {
        
        byte data[] = new byte[1024];
        int count = 0;
        int word = -1;
        
        //解析第一行
        while ((word = receiver.read()) != -1)
        {
            if (word == '\r' || word == '\n')
            {
                word = receiver.read();
                if (word == '\n')
                    word = receiver.read();
                break;
            }
            if (count == data.length)
                data = addCapacity(data);//数据长度超限时增加内存分配
            data[count++] = (byte) word;
        }
        String message = new String(data, 0, count);
        
        int mark = message.indexOf(32);
        serverVersion = message.substring(0, mark);
        System.out.println(message);
        while (mark < message.length() && message.charAt(mark + 1) == 32)
            mark++;
        responseCode = Integer.parseInt(message.substring(mark + 1, mark += 4));
        responseMessage = message.substring(mark, message.length()).trim();
        
        //应答状态码和处理请读者添加
        switch (responseCode)
        {
        case 400:
            throw new IOException("错误请求");
        case 404:
            throw new FileNotFoundException(getURLFormat(target));
        case 503:
            throw new IOException("服务器不可用");
        }
        if (word == -1)
            throw new ProtocolException("信息接收异常终止");
        int symbol = -1;
        count = 0;
        //解析元信息
        while (word != '\r' && word != '\n' && word > -1)
        {
            
            if (word == '\t')
                word = 32;
            if (count == data.length)
                data = addCapacity(data);
            data[count++] = (byte) word;
            parseLine:
            {
                while ((symbol = receiver.read()) > -1)
                {
                    switch (symbol)
                    {
                    case '\t':
                        symbol = 32;
                        break;
                    case '\r':
                    case '\n':
                        word = receiver.read();
                        if (symbol == '\r' && word == '\n')
                        {
                            word = receiver.read();
                            if (word == '\r')
                                word = receiver.read();
                        }
                        if (word == '\r' || word == '\n' || word > 32)
                            break parseLine;
                        symbol = 32;
                        break;
                    }
                    if (count == data.length)
                        data = addCapacity(data);
                    data[count++] = (byte) symbol;
                }
                word = -1;
            }
            message = new String(data, 0, count);
            System.out.println(message);
            mark = message.indexOf(':');
            String key = null;
            if (mark > 0)
                key = message.substring(0, mark);
            mark++;
            while (mark < message.length() && message.charAt(mark) <= 32)
                mark++;
            String value = message.substring(mark, message.length());
            header.put(key, value);
            count = 0;
        }
        /*
        //获得正文数据
        while ((word = receiver.read()) != -1)
        {
            System.out.println("char:"+word);
            if (count == data.length)
                data = addCapacity(data);
            data[count++] = (byte) word;
        }
        */
        content="";
        byte temp[]=new byte[512];
        while ((receiver.read(temp)) != -1)
        {
            String part=new String(temp);
            System.out.println("......:"+part);
           // if (count == data.length)
            //    data = addCapacity(data);
            content+=part;
            if((part.indexOf("</html>")!=-1)||(part.indexOf("</HTML>")!=-1))
            {
                System.out.println("find:.:"+part);
                break;
            }
            // data[count++] = temp;
        }
        if (count > 0)
        {
         //   byteStream = new ByteArrayInputStream(data, 0, count);
       //     content=new String(data);
        }
      //  System.out.println("Line(body):");
      //  System.out.println(new String(data));
        data = null;
        closeServer();
    }

    public String getResponseMessage()
    {
        return responseMessage;
    }

    public int getResponseCode()
    {
        return responseCode;
    }

    public String getServerVersion()
    {
        return serverVersion;
    }

  //  public InputStream getInputStream()
    {
     //   return byteStream;
    }

    public synchronized String getHeaderKey(int i)
    {
        if (i >= header.size())
            return null;
        Enumeration enumm = header.propertyNames();
        String key = null;
        for (int j = 0; j <= i; j++)
            key = (String) enumm.nextElement();
        return key;
    }

    public synchronized String getHeaderValue(int i)
    {
        if (i >= header.size())
            return null;
        return header.getProperty(getHeaderKey(i));
    }

    public synchronized String getHeaderValue(String key)
    {
        return header.getProperty(key);
    }

    
    public String getContent()
    {
        return content;
    }
    private byte[] addCapacity(byte rece[])
    {
        byte temp[] = new byte[rece.length + 1024];
        System.arraycopy(rece, 0, temp, 0, rece.length);
        return temp;
    }

    /* 
     * GET / HTTP/1.1
     * Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-powerpoint, application/vnd.ms-excel, application/msword, *\/*
     * Accept-Language: zh-cn
       Accept-Encoding: gzip, deflate
       User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; Maxthon)
       Host: www.google.com
       Connection: Keep-Alive
     */
    protected String getBaseHeads()
    {
        String inf = 
         "Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-powerpoint, application/vnd.ms-excel, application/msword, */*\r\n"
        + "Accept-Language: zh-cn\r\n"
        + "Accept-Encoding: gzip, deflate\r\n"
        + "User-Agent:Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; Maxthon)\r\n"
        + "Host:"+target.getHost()+"\r\n"
        + "Connection: Keep-Alive\r\n";

        
        return inf;
    }
    public String getTest()
    {
        String test="GET /vote.jsp?flag=0&username=........&0.4993486728853603 HTTP/1.1"
            +"Accept: *//*"

            +"accept-language: zh-cn"

            +" referer: http://ji.mop.com/htm/search.jsp"

            +" content-type: application/x-www-form-urlencoded"

            +"Accept-Encoding: gzip, deflate"

            +"User-Agent: Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0; Maxthon)"

            +"Host: ji.mop.com"

            +"Connection: Keep-Alive"

            +"Cookie: mop_uniq_ckid=222.183.103.143_1146734650_1264285702; mop_logon=9850287%7Ckofsky%7Ckofsky%7C20060607043810%7CEDB3D4037660F253CBA42B1BBFDC41B7; mop_status=55O52O58O51O50O58O52O48O32O55O48O45O54O48O45O54O48O48O50O124O57O54O124O50O52O49O46O53O55O46O51O56O49O46O50O50O50O124O21513O22823O124O24120O27491O124O48O124O50O49O50O124O121O107O115O102O111O107O124O121O107O115O102O111O107; JSESSIONID=ah-iFpmE2xm9"
            ;
        return test;
    }


    public static void main(String[] args)
    {
        HTTPTest http = new HTTPTest();
        //http.GET("http://192.168.1.5");
        int i;

        //  http.GET("http://202.202.12.10/dz1.php");
        //  http.GET("http://www.sina.com.cn/");
          http.GET("http://www.tom.com/");
        //  http.GET("http://sports.tom.com/2006-04-27/08EL/74650308.html");
        //  http.GET("http://blog.tianya.cn/blogger/view_blog.asp?BlogName=kofsky");
    //    System.out.println(http.getContent());
    }

}

⌨️ 快捷键说明

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