NIO--SocketChannel发送HTTP请求


import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;

/**
 * Created with .
 * Date: 14-5-27
 * Time: 上午11:38
 * To change this template use File | Settings | File Templates.
 */
public class HttpTest {


    private static byte[] request = null;

    static {
        StringBuffer temp = new StringBuffer();
        temp.append("GET http://localhost:8080/feifei/helloStruts-sayHello.action HTTP/1.1\r\n");
        temp.append("Host: 127.0.0.1:8080\r\n");
        temp.append("Connection: keep-alive\r\n");
        temp.append("Cache-Control: max-age=0\r\n");
        temp
                .append("User-Agent: Mozilla/5.0 (Windows NT 5.1) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.47 Safari/536.11\r\n");
        temp
                .append("Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n");
        temp.append("Accept-Encoding: gzip,deflate,sdch\r\n");
        temp.append("Accept-Language: zh-CN,zh;q=0.8\r\n");
        temp.append("Accept-Charset: GBK,utf-8;q=0.7,*;q=0.3\r\n");
        temp.append("\r\n");
        request = temp.toString().getBytes();
    }

    public static void sendHttpRequest() throws Exception {
        try {

            final SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("localhost", 8080));
            final Charset charset = Charset.forName("GBK");// 创建GBK字符集
            socketChannel.configureBlocking(false);//配置通道使用非阻塞模式

            while (!socketChannel.finishConnect()) {
                Thread.sleep(10);
            }
            //proxySocketChannel.write(charset.encode("GET " + "http://localhost:8080/feifei/helloStruts-sayHello.action HTTP/1.1" + "\r\n\r\n"));
            socketChannel.write(ByteBuffer.wrap(request));

            int read = 0;
            boolean readed = false;
            ByteBuffer buffer = ByteBuffer.allocate(1024);// 创建1024字节的缓冲
            while ((read = socketChannel.read(buffer)) != -1) {
                if (read == 0 && readed) {
                    break;
                } else if (read == 0) {
                    continue;
                }

                buffer.flip();// flip方法在读缓冲区字节操作之前调用。
                System.out.println(charset.decode(buffer));
                // 使用Charset.decode方法将字节转换为字符串
                buffer.clear();// 清空缓冲
                readed = true;
            }
            System.out.println("----------------");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception {
        sendHttpRequest();
    }


}





  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值