用java.net.HttpURLConnection之类的类来获取读取

解决方案 »

  1.   

    public static void getURL(String url, OutputStream out) throws Exception
    {
    // 创建URL对象
    URL http_URL = new URL(url);
    // 请求协议
    String protocol = http_URL.getProtocol();
    // 服务器主机名称
    String host = http_URL.getHost();
    // 请求的文件名称
    String filename = http_URL.getFile();
    // 端口
    int port = http_URL.getPort();

    // 如果不是http请求
    if (!protocol.equals("http"))
    {
    // 抛出异常
    throw new IllegalArgumentException("仅仅支持http请求协议");
    }
    // 请求的服务器主机名称为null
    if (host == null) { 
    throw new IllegalArgumentException("无效的服务主机帐户");
    } //建立底层的Socket通讯
    Socket socket = new Socket(host, port);
    //得到输入流数据
    InputStream from = socket.getInputStream();
    //构造http请求头

    PrintWriter to = new PrintWriter(socket.getOutputStream());
    //设置http请求头类型及信息
    to.print("GET " + filename + " HTTP/1.0\n");
    to.print("Accept: */*\n");
    to.print("Accept-Language: zh-cn\n");
    to.print("Accept-Encoding: gb2312, deflate\n");
    to.print("User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)\n");
    to.print("Host: " + http_URL.getHost() + "\n");
    to.print("Connection: Keep-Alive\n\n");
    to.flush();
    byte[] buf = new byte[4096];
    int bytes_read;
    //读取数据流
    while ((bytes_read = from.read(buf)) != -1)
    {
    out.write(buf, 0, bytes_read);
    }
    //关闭socket通讯,及数据流对象
    socket.close();
    out.close();
    }

    /**
    * 得到请求的页面信息
    */
    public static String getRequestPage(String url)
    {
    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    //返回的html代码
    String html = "";
    try
    {
    //要读取的页面地址
    getURL(url, outStream);
    html = outStream.toString().toLowerCase();
    }
    catch (IOException e)
    {
    //.....
    }
    catch (Exception e)
    {
    e.printStackTrace();
    }
    return html;
    }