进入旧版 | 服务项目 | 成功案例 | 联系方式 | 过客留言 | 友情链接
   
设为首页
加入收藏
联系我们
网站首页 | 新闻资讯 | 操作系统 | 办公软件 | 网络软件 | 工具软件 | 媒体动画 | 网页制作 | 网站开发 | 程序开发 | 平面设计
Photoshop视频教程 | Word入门 | Flash入门 | JScript | VBScript | ASP | PHP | ADO | 网页特效 | 3DS MAX6.0命令 | 系统进程
您当前的位置:GOODSGY电脑学习网 -> 网站开发 -> JSP -> 文章内容  
一个用来访问http服务器的东西。功能类似于java.net中的那个。但要强。

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;
    }
}

在百度中搜索:一个用来访问http服务器的东西。功能类似于java.net中的那个。但要强。
在Google中搜索:一个用来访问http服务器的东西。功能类似于java.net中的那个。但要强。
在Yahoo中搜索:一个用来访问http服务器的东西。功能类似于java.net中的那个。但要强。

收藏到网摘:新浪VIVI 365key 我摘 POCO网摘 博采中心 YouNote 和讯网摘 天天收藏
[] [返回上一页] [打 印] [收 藏]
下一篇文章:java的md5加密类(zt)

 相关文章    最新文章
· 初学ASP编程易犯的一个错误要注意
· 一个合格网页设计师的标准是什么?
· [组图] 成为一个顶级设计师的第二准则
· 比尔·盖茨:下一个数字化十年将更美好
· 建立一个安全Linux服务器
· 如何恢复一个已破坏的OfficeWord文档
· 打造一个稳定的Maxthon2 拒绝假死崩溃
· [图文] 仅需一个公式 让Excel按人头打出工..
· XP中的一个秘密武器,可以完整清除垃圾文..
· IE浏览器中一个值得关注的JS问题
 
· 提升JSP页面响应速度的七大秘籍绝招
· 开发一个调试JSP的Eclipse插件
· JSP报表打印的一种简单解决方案
· JSP/Servlet的重定向技术综述
· java的md5加密类(zt)
· 一个用来访问http服务器的东西。功能类似..
· 菜鸟调试手记一(sql server 中文问题)
· Java性能优化技巧集锦(2)
· 用java压缩文件示例(没有中文问题)
· 使用XML/HTC/DHTML模拟标准Windows菜单

∷相关文章评论∷    (评论内容只代表网友观点,与本站立场无关!) [更多评论…]
站内搜索

精彩图文
  网站导航  
操作系统 办公软件 网络软件
Vista Windows2003 WindowsXP Windows2000/NT Windows9X/ME Linux 其他 Word Excel Powerpoint Outlook 金山系列 其他 网页浏览 上传下载 联络聊天 邮件工具 服务器软件 网络辅助
工具软件 媒体动画 网页制作
系统工具 媒体工具 压缩工具 图文处理 文件管理 其他 3DMAX Authorware Director Maya 视频处理 其他 Flash Dreamweaver FireWorks FrontPage LiveMotion Golive HTML/CSS 其它
网站开发 平面设计 程序设计
ASP JSP PHP CGI JavaScript VBScript XML/SOAP Web服务器 Photoshop PhotoImpact CorelDraw Illustrator Freehand 设计欣赏 其他 VB VC .NET C/C++ DELPHI JAVA

冀ICP备05019428号
Copyright © 2004-2008 电脑学习网 Inc.All rights reserved.
TEL:13832340607
QQ:39873155
E_Mail:goodsgy(#)hotmail.com   (把(#)替换成@)
MSN:goodsgy(#)hotmail.com   (把(#)替换成@)