• 软件测试技术
  • 软件测试博客
  • 软件测试视频
  • 开源软件测试技术
  • 软件测试论坛
  • 软件测试沙龙
  • 软件测试资料下载
  • 软件测试杂志
  • 软件测试人才招聘
    暂时没有公告

字号: 小 中 大 | 推荐给好友 上一篇 | 下一篇

基于NIO实现客户端通过HTTP协议访问WEB站点

发布: 2007-7-04 13:34 | 作者: admin | 来源:  网友评论 | 查看: 9次 | 进入软件测试论坛讨论

领测软件测试网 这只是一个简单的示例,如果你想了解HTTP的详细内容可参考我的一个开源项目JQuickDown

/*
* Created on 2005-2-1
*
* CopyRight by lxleaves_zhang
*/
package test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.channels.spi.SelectorProvider;
import java.util.Iterator;

public class NIOTest {
public static SocketChannel createSocketChannel(String host, int port)
throws IOException {
SocketChannel sc = SocketChannel
.open(new InetSocketAddress(host, port));
sc.configureBlocking(false);
return sc;
}

public static final String host = "www.163.com";

public static final String path = "/";

public static final int port = 80;

public static final byte[] req = ("GET " + path + " HTTP/1.0\r\nHost:"
+ host + "\r\n\r\n").getBytes();

public static void main(String[] args) {
Selector sel = null;
ByteBuffer buf = ByteBuffer.allocate(256);
SocketChannel sc[] = new SocketChannel[2];
try {
sel = SelectorProvider.provider().openSelector();
sc[0] = createSocketChannel(host, port);
sc[1] = createSocketChannel(host, port);
buf.put(req);
buf.flip();
sc[0].write(buf);
buf.flip();
sc[1].write(buf);
sc[0].register(sel, sc[0].validOps());
sc[1].register(sel, sc[1].validOps());
} catch (IOException e) {
e.printStackTrace();
}
while (sel.isOpen()) {
try {
sel.select();
} catch (IOException e) {
e.printStackTrace();
}
Iterator it = sel.selectedKeys().iterator();
while (it.hasNext()) {
SelectionKey sk = (SelectionKey) it.next();
it.remove();
SocketChannel next = (SocketChannel) sk.channel();
buf.clear();
try {
// check whether finish
if (next.read(buf) == -1) {
sk.cancel();
next.close();

if (!it.hasNext()) {
sel.close();
}
}
} catch (IOException e) {
e.printStackTrace();
}
buf.flip();
if (buf.limit() == 0)
continue;
byte b[] = new byte[buf.limit()];
buf.get(b);
// System.out.println(next == sc[0]);
if (next == sc[0])
System.out.print(new String(b));
else
System.err.print(new String(b));
}
}
}
}



文章来源于领测软件测试网 https://www.ltesting.net/


关于领测软件测试网 | 领测软件测试网合作伙伴 | 广告服务 | 投稿指南 | 联系我们 | 网站地图 | 友情链接
版权所有(C) 2003-2010 TestAge(领测软件测试网)|领测国际科技(北京)有限公司|软件测试工程师培训网 All Rights Reserved
北京市海淀区中关村南大街9号北京理工科技大厦1402室 京ICP备10010545号-5
技术支持和业务联系:[email protected] 电话:010-51297073

软件测试 | 领测国际 | ISTQB | ISTQB官网 | TMMi | TMMi认证 | 国际软件测试工程师认证 | 领测软件测试网