简单网页内容下载 NIO

这个例子非常简单,类SocketChannelReader使用SocketChannel来下载特定网页的HTML内容。
package examples.nio;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.net.InetSocketAddress;
import java.io.IOException;
public class SocketChannelReader{

private Charset charset=Charset.forName("UTF-8");// 创建UTF-8字符集
private SocketChannel channel;
public void getHTMLContent(){
try{
connect();
sendRequest();
readResponse();
}catch(IOException e){
System.err.println(e.toString());
}finally{
if(channel!=null){
try{
channel.close();
}catch(IOException e){}
}
}
}
private void connect()throws IOException{// 连接到 CSDN
InetSocketAddress socketAddress=
new InetSocketAddress("http://www.csdn.net",80/);
channel=SocketChannel.open(socketAddress);
//使用工厂方法open创建一个channel并将它连接到指定地址上
// 相当与SocketChannel.open().connect(socketAddress);调用
}
private void sendRequest()throws IOException{
channel.write(charset.encode("GET "
+"/document"
+"\r\n\r\n"));// 发送GET请求到CSDN的文档中心
// 使用channel.write方法,它需要CharByte类型的参数,使用
//Charset.encode(String) 方法转换字符串。
}
private void readResponse()throws IOException{// 读取应答
ByteBuffer buffer=ByteBuffer.allocate(1024);// 创建1024字节的缓冲
while(channel.read(buffer)!=-1){
buffer.flip();//flip 方法在读缓冲区字节操作之前调用。
System.out.println(charset.decode(buffer));
// 使用Charset.decode方法将字节转换为字符串
buffer.clear();// 清空缓冲
}
}
public static void main(String [] args){
new SocketChannelReader().getHTMLContent();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值