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(); } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通