使用java.nio及其子包中的类SocketChanel完成如下功能:读取www.baidu.com等网页的内容,打印到控制台,避免中文乱码问题。
2015-08-12 21:58
866 查看
package test;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
public class NioHtmlReader {
private Charset charset = Charset.forName("GBK");// 创建GBK字符集
private SocketChannel channel;
public void readHTMLContent(String url, int port) {
try {
InetSocketAddress socketAddress = new InetSocketAddress(url, port);
// 1 打开连接
channel = SocketChannel.open(socketAddress);
// 2 发送请求,使用GBK编码
channel.write(charset.encode("GET" + "/HTTP/1.1" + "\r\n\r\n"));
// 3 读取数据, 创建1024字节的缓冲
ByteBuffer buffer = ByteBuffer.allocate(1024);
while (channel.read(buffer) != -1) {
// flip方法在读缓冲区字节操作之前调用
buffer.flip();
// 使用Charset.decode方法将字节转换为字符串
System.out.println(charset.decode(buffer));
// 清空缓冲
buffer.clear();
}
} catch (Exception e) {
System.err.println(e.toString());
} finally {
if (channel != null) {
try {
channel.close();
} catch (IOException e) {
}
}
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
new NioHtmlReader().readHTMLContent("
www.baidu.com", 80);
}
}
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
public class NioHtmlReader {
private Charset charset = Charset.forName("GBK");// 创建GBK字符集
private SocketChannel channel;
public void readHTMLContent(String url, int port) {
try {
InetSocketAddress socketAddress = new InetSocketAddress(url, port);
// 1 打开连接
channel = SocketChannel.open(socketAddress);
// 2 发送请求,使用GBK编码
channel.write(charset.encode("GET" + "/HTTP/1.1" + "\r\n\r\n"));
// 3 读取数据, 创建1024字节的缓冲
ByteBuffer buffer = ByteBuffer.allocate(1024);
while (channel.read(buffer) != -1) {
// flip方法在读缓冲区字节操作之前调用
buffer.flip();
// 使用Charset.decode方法将字节转换为字符串
System.out.println(charset.decode(buffer));
// 清空缓冲
buffer.clear();
}
} catch (Exception e) {
System.err.println(e.toString());
} finally {
if (channel != null) {
try {
channel.close();
} catch (IOException e) {
}
}
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
new NioHtmlReader().readHTMLContent("
www.baidu.com", 80);
}
}
相关文章推荐
- Java IO 总结
- Java多线程(4)----线程的四种状态
- Spring入门教程(一)IOC 基本概念
- spring版本区别
- spring 整合 spring mvc
- java复习-泛型
- 有向图闭环检测值java代码实现
- Eclipse小技巧
- java中this的用法小结
- Eclipse工程出现红叉
- jdk版本的特点
- Java学习之路0812(doGet和doPost)
- Java学习之路0811(预编译、事务、web项目)
- 【Struts2学习笔记-4】包含其他配置文件
- Eclipse 调试jar包源码
- JAVA 访问 SOAP 协议
- 关于Spring中AOP的几种拦截方式
- Springmvc构造RESTful详细讲解
- 【Struts2学习笔记-3】常量配置
- Spring-MVC环境搭建