用来访问HTTP服务器的仿java.net功能类

开发
一个用来访问http服务器的东西。功能类似于java.net中的那个,但这个对Post方法的支持更好。

下面这段代码用来访问HTTP服务器,比Java.net中对Post方法的支持的更好。

package net.sonyhome.net;

import java.io.*;
import java.net.*;
import java.util.*;
import java.text.*;

public class HttpConnection {
    private URL url = null;
    //private boolean doInput = true;
    //private boolean doOutput = true;

    private boolean usePost = false;

    private boolean useCaches = false;

    private Vector reqHeaderNames = new Vector();
    private Vector reqHeaderValues = new Vector();
    private Vector resHeaderNames = null;
    private Vector resHeaderValues = null;
    private Socket socket = null;
    private OutputStream out = null;
    private InputStream in = null;
    private boolean useHttp11 = false;

    private boolean connected = false;

    private boolean inputStarted = false;

    Hashtable postData = new Hashtable();
    Hashtable getData = new Hashtable();

    /**
     * HttpConnection constructor comment.
     */
    public HttpConnection(URL url) {
        super();
        this.url = url;
    }
    /**
     * Insert the method@#s description here.
     * @param name java.lang.String
     * @param value java.lang.String
     */
    public void addGet(String name, String value) {
        getData.put(name, value);
    }
    /**
     * Insert the method@#s description here.
     * @param name java.lang.String
     * @param value java.lang.String
     */
    public void addPost(String name, String value) {
        postData.put(name, value);
    }
    public void close() throws IOException {
        if (!connected)
            return;
        out.close();
        if (inputStarted)
            in.close();
        socket.close();
    }
    public void connect() throws IOException {
        if (connected)
            return;
        if (!useCaches) {
            setRequestProperty("Pragma", "no-cache");
            //setRequestProperty("Cache-Control", "no-cache, must-revalidate");
            //setRequestProperty("Expires", "Mon, 26 Jul 1997 05:00:00 GMT");
        }
        String protocol = url.getProtocol();
        if (!protocol.equals("http"))
            throw new UnknownServiceException("unknown protocol");
        String host = url.getHost();
        int port = url.getPort();
        if (port == -1)
            port = 80;
        String file = url.getFile();

        socket = new Socket(host, port);
        out = socket.getOutputStream();
        PrintStream pout = new PrintStream(out);

        String method;
        if (usePost) {
            method = "POST";
            setRequestProperty("Content-type", "application/x-www-form-urlencoded");
            int len = getPostDataLength();
            setRequestProperty("Content-length", String.valueOf(getPostDataLength()));

        }
        else
            method = "GET";
        if (getGetDataLength() > 0) {
            file += "?" + getGetDataString();
        }
        pout.println(method + " " + file + " HTTP/1.0");

        for (int i = 0; i < reqHeaderNames.size(); ++i) {
            String name = (String) reqHeaderNames.elementAt(i);
            String value = (String) reqHeaderValues.elementAt(i);
            pout.println(name + ": " + value);
        }
        pout.println("");
        if (usePost) {
            String ttt = getPostDataString();
            pout.println(getPostDataString());
        }

        pout.flush();

        connected = true;
    }
    /**
     * Insert the method@#s description here.
     * @return boolean
     * @exception java.lang.IllegalStateException The exception description.
     */
    public boolean contentIsText() throws IOException {
        String type = getContentType();
        if (type.startsWith("text"))
            return true;
        return false;
    }
    /**
     * Insert the method@#s description here.
     * @return byte[]
     */
    public byte[] getByteArray() throws IOException {
        DataInputStream din = new DataInputStream(getInputStream());

        byte[] ret;
        byte[] b = new byte[1024];
        int off = 0, len = 0;

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((len = din.read(b, off, 1024)) > 0) {
            bos.write(b, 0, len);
            if (len < 1024)
                break;
        }
        bos.flush();
        bos.close();
        return bos.toByteArray();
    }
    // Gets the content length.  Returns -1 if not known.
    public int getContentLength() throws IOException {
        return getHeaderFieldInt("content-length", -1);
    }
    /// Gets the content type.  Returns null if not known.
    public String getContentType() throws IOException {
        return getHeaderField("content-type");
    }
    /**
     * Insert the method@#s description here.
     * @return java.lang.String
     */
    public int getGetDataLength() {
        return getGetDataString().length();
    }
    /**
     * Insert the method@#s description here.
     * @return java.lang.String
     */
    public String getGetDataString() {
        StringBuffer buf = new StringBuffer();
        Enumeration enu = getData.keys();
        while (enu.hasMoreElements()) {
            String key = (String) (enu.nextElement());
            String value = (String) (getData.get(key));
            if (buf.length() > 0)
                buf.append("&");
            buf.append(key);
            buf.append("=");
            buf.append(URLEncoder.encode(value));
        }
        return buf.toString();
    }
    public String getHeaderField(String name) throws IOException {
        if (resHeaderNames == null)
            startInput();
        int i = resHeaderNames.indexOf(name.toLowerCase());
        if (i == -1)
            return null;
        return (String) resHeaderValues.elementAt(i);
    }
    public long getHeaderFieldDate(String name, long def) throws IOException {
        try {
            return DateFormat.getDateInstance().parse(getHeaderField(name)).getTime();
        }
        catch (ParseException e) {
            throw new IOException(e.toString());
        }
    }
    public int getHeaderFieldInt(String name, int def) throws IOException {
        try {
            return Integer.parseInt(getHeaderField(name));
        }
        catch (NumberFormatException t) {
            return def;
        }
    }
    /**
     * Insert the method@#s description here.
     * @return java.util.Enumeration
     */
    public Enumeration getHeaderNames() {
        return resHeaderNames.elements();
    }
    public InputStream getInputStream() throws IOException {
        startInput();
        return in;
    }
    public OutputStream getOutputStream() throws IOException {
        connect();
        return out;
    }
    /**
     * Insert the method@#s description here.
     * @return java.lang.String
     */
    public int getPostDataLength() {
        return getPostDataString().length();
    }
    /**
     * Insert the method@#s description here.
     * @return java.lang.String
     */
    public String getPostDataString() {
        StringBuffer buf = new StringBuffer();
        Enumeration enu = postData.keys();
        while (enu.hasMoreElements()) {
            String key = (String) (enu.nextElement());
            String value = (String) (postData.get(key));
            if (buf.length() > 0)
                buf.append("&");
            buf.append(key);
            buf.append("=");
            buf.append(URLEncoder.encode(value));
        }
        return buf.toString();
    }
    public String getRequestProperty(String name) {
        if (connected)
            throw new IllegalAccessError("already connected");
        int i = reqHeaderNames.indexOf(name);
        if (i == -1)
            return null;
        return (String) reqHeaderValues.elementAt(i);
    }
    public URL getURL() {
        return url;
    }
    public boolean getUseCaches() {
        return useCaches;
    }
    public boolean getUseHttp11() {
        return useHttp11;
    }
    /**
     * Insert the method@#s description here.
     * @return boolean
     */
    public boolean isUsePost() {
        return usePost;
    }
    /**
     * Insert the method@#s description here.
     * @param args java.lang.String[]
     */
    public static void main(String[] args) {
        try {
            /*
            URL url=new URL("http","192.168.0.3","/Post.php");
            HttpConnection con=new HttpConnection(url);
            con.setUsePost(true);
            con.setUseCaches(false);
            //con.setRequestProperty("Connection", "Keep-Alive");
           
            con.addGet("TextField","你好");
            con.addGet("Submit", "submit");
           
            con.connect();
            //ByteArrayOutputStream bos=con.getByteArray();
            byte[] ret=con.getByteArray();
            System.out.println(new String(ret));
           
            System.out.println("");
            Enumeration enu=con.getHeaderNames();
            while (enu.hasMoreElements()) {
                String headerName=(String)(enu.nextElement());
                System.out.println(headerName+": "+con.getHeaderField(headerName));
            }
            con.close();
            */

            URL url = new URL("http", "192.168.0.3", "/codemaker/IMAGES/BO.GIF");
            HttpConnection con = new HttpConnection(url);
            con.connect();

            FileOutputStream fos = new FileOutputStream("d:\\bo.gif");
            fos.write(con.getByteArray());
            fos.flush();
            fos.close();

            System.out.println("");
            Enumeration enu = con.getHeaderNames();
            while (enu.hasMoreElements()) {
                String headerName = (String) (enu.nextElement());
                System.out.println(headerName + ": " + con.getHeaderField(headerName));
            }
            con.close();

        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * Insert the method@#s description here.
     * @param name java.lang.String
     * @param value java.lang.String
     */
    public void removeGet(String name) {
        getData.remove(name);
    }
    /**
     * Insert the method@#s description here.
     * @param name java.lang.String
     * @param value java.lang.String
     */
    public void removePost(String name) {
        postData.remove(name);
    }
    public void setRequestProperty(String name, String value) {
        if (connected)
            throw new IllegalAccessError("already connected");
        reqHeaderNames.addElement(name);
        reqHeaderValues.addElement(value);
    }
    public void setUseCaches(boolean useCaches) {
        if (connected)
            throw new IllegalAccessError("already connected");
        this.useCaches = useCaches;
    }
    public void setUseHttp11(boolean useHttp11) {
        if (connected)
            throw new IllegalAccessError("already connected");
        this.useHttp11 = useHttp11;
    }
    /**
     * Insert the method@#s description here.
     * @param newUsePost boolean
     */
    public void setUsePost(boolean newUsePost) {
        if (connected)
            throw new IllegalAccessError("already connected");
        usePost = newUsePost;
    }
    private void startInput() throws IOException {
        connect();
        if (inputStarted)
            return;
        in = socket.getInputStream();
        resHeaderNames = new Vector();
        resHeaderValues = new Vector();
        DataInputStream din = new DataInputStream(in);
        String line;

        // Read and ignore the status line.
        line = din.readLine();
        // Read and save the header lines.
        while (true) {
            line = din.readLine();
            if (line == null || line.length() == 0)
                break;
            int colonBlank = line.indexOf(": ");
            if (colonBlank != -1) {
                String name = line.substring(0, colonBlank);
                String value = line.substring(colonBlank + 2);
                resHeaderNames.addElement(name.toLowerCase());
                resHeaderValues.addElement(value);
            }
        }

        inputStarted = true;
    }
    /**
     * Returns a String that represents the value of this object.
     * @return a string representation of the receiver
     */
    public String toString() {
        // Insert code to print the receiver here.
        // This implementation forwards the message to super. You may replace or supplement this.
        return this.getClass().getName() + ":" + url;
    }
}

责任编辑:王观 来源: 百家编程
相关推荐

2011-08-01 16:07:53

文件服务器

2010-07-02 09:56:16

2010-05-25 13:49:11

访问SVN服务器

2010-07-26 12:30:11

Telnet服务器

2010-05-25 14:02:54

Http访问SVN服务

2019-08-22 15:26:24

HTTP服务器Python

2019-07-04 15:00:32

PythonHTTP服务器

2010-03-22 12:57:46

Java Socket

2017-11-10 08:58:49

Web服务器应用程序

2018-10-09 09:28:12

HTTPHTTP协作服务器

2009-07-03 13:05:47

JSP HTTP服务器

2009-02-27 13:53:00

远程服务器RAS

2012-02-27 13:56:19

Java服务器

2009-07-06 17:56:12

JSP HTTP服务器

2019-04-23 10:48:55

HTTPTomcat服务器

2018-01-19 10:30:48

HTTP服务器代码

2022-02-11 11:22:03

云服务器物理服务器服务器

2009-07-06 17:46:25

JSP HTTP服务器

2022-08-28 10:47:22

Ubuntu

2011-08-08 14:46:15

服务器跨网访问控制
点赞
收藏

51CTO技术栈公众号