当前位置:首页 > 编程开发

使用Socket通道读取web页面

webgou17年前 (2009-10-10)编程开发118

http://www.99inf.net/SoftwareDev/Java/48705.htm
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;

public class GetWebPageDemo {
  public static void main(String args[]) throws Exception {
    String resource, host, file;
    int slashPos;

    resource = "www.java2s.com/index.htm";
    slashPos = resource.indexOf('/'); // find host/file separator
    if (slashPos < 0) {
      resource = resource + "/";
      slashPos = resource.indexOf('/');
    }
    file = resource.substring(slashPos); // isolate host and file parts
    host = resource.substring(0, slashPos);
    System.out.println("Host to contact: '" + host + "'");
    System.out.println("File to fetch : '" + file + "'");

    SocketChannel channel = null;

    try {
      Charset charset = Charset.forName("ISO-8859-1");
      CharsetDecoder decoder = charset.newDecoder();
      CharsetEncoder encoder = charset.newEncoder();

      ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
      CharBuffer charBuffer = CharBuffer.allocate(1024);

      InetSocketAddress socketAddress = new InetSocketAddress(host, 80);
      channel = SocketChannel.open();
      channel.connect(socketAddress);

      String request = "GET " + file + " \r\n\r\n";
      channel.write(encoder.encode(CharBuffer.wrap(request)));

      while ((channel.read(buffer)) != -1) {
        buffer.flip();
        decoder.decode(buffer, charBuffer, false);
        charBuffer.flip();
        System.out.println(charBuffer);
        buffer.clear();
        charBuffer.clear();
      }
    } catch (UnknownHostException e) {
      System.err.println(e);
    } catch (IOException e) {
      System.err.println(e);
    } finally {
      if (channel != null) {
        try {
          channel.close();
        } catch (IOException ignored) {
        }
      }
    }

    System.out.println("\nDone.");
  }

扫描二维码推送至手机访问。

版权声明:本文由知了博客发布,如需转载请注明出处。

本文链接:https://www.webgou.info/?id=40

标签: javasocket
分享给朋友:

“使用Socket通道读取web页面” 的相关文章

Android数据库相关代码解读(1)

昨天进行了GUI界面设计,感受了一下android初次设计的愉悦,今天接着学习其SQLite数据库试用,将昨天的例子中数据存到数库中,并读取查看一下。 具体看代码(原写的有点问题,再改写如下):1) Android数据库之库操作类:package com.topsun;  &nb…

Google Chrome Source Code 源码下载

Google Chrome Source Code 源码下载…

5 Ways to Make HTTP Requests in Node.js

 HTTP – the Standard LibraryFirst on our hit parade is the default HTTP module in the standard library. With th…

Android平台值得关注的开源项目

Android开发又将带来新一轮热潮,很多开发者都投入到这个浪潮中去了,创造了许许多多相当优秀的应用。下面推荐几个应用开源项目,这些项目不仅提供了优秀的创意,也可以直接掌握 Android内核的接口使用:1.Android团队提供的示例项目...…

递归逆转字符串

string RecuriseRevalsal(string &s)...{ if(s.size()˃1) ...{ string::iterator i = s.begin(); char end = *i; ...…

发表评论

访客

看不清,换一张

◎欢迎参与讨论,请在这里发表您的看法和观点。