首页 > 开发 > Java > 正文

功能类似于java.net访问http服务器程序

2024-07-13 09:55:38
字体:
来源:转载
供稿:网友
  • 本文来源于网页设计爱好者web开发社区http://www.html.org.cn收集整理,欢迎访问。
  • package net.sonyhome.net;

    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.text.*;
    /**
    * 一个用来访问http服务器的东西。功能类似于java.net中的那个。但要强,这个对post方法的支持更好。
    * 其实也不能说是我写的。不记得从哪儿找来的程序,稍事修改了一下。所以现在程序的结构都忘啦。
    * 不过有一点是肯定的,那就是可以用。呵呵。
    * 去年我做的java版的精华区就是用这个类来访问的。
    * creation date: (2001-8-24 23:57:14)
    * @author: sonymusic
    */
    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.
         * creation date: (2001-8-25 1:16:52)
         * @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.
         * creation date: (2001-8-25 1:16:52)
         * @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.
         * creation date: (2001-8-25 2:06:07)
         * @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.
         * creation date: (2001-8-25 2:20:31)
         * @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.
         * creation date: (2001-8-25 1:18:23)
         * @return java.lang.string
         */
        public int getgetdatalength() {
            return getgetdatastring().length();
        }
        /**
         * insert the method's description here.
         * creation date: (2001-8-25 1:18:23)
         * @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.
         * creation date: (2001-8-25 1:12:09)
         * @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.
         * creation date: (2001-8-25 1:18:23)
         * @return java.lang.string
         */
        public int getpostdatalength() {
            return getpostdatastring().length();
        }
        /**
         * insert the method's description here.
         * creation date: (2001-8-25 1:18:23)
         * @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.
         * creation date: (2001-8-25 1:48:15)
         * @return boolean
         */
        public boolean isusepost() {
            return usepost;
        }
        /**
         * insert the method's description here.
         * creation date: (2001-8-25 0:15:53)
         * @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.
         * creation date: (2001-8-25 1:16:52)
         * @param name java.lang.string
         * @param value java.lang.string
         */
        public void removeget(string name) {
            getdata.remove(name);
        }
        /**
         * insert the method's description here.
         * creation date: (2001-8-25 1:16:52)
         * @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.
         * creation date: (2001-8-25 1:48:15)
         * @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;
        }
    }
    发表评论 共有条评论
    用户名: 密码:
    验证码: 匿名发表