栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java之使用socket连接http接口

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java之使用socket连接http接口

Java之使用socket连接http接口
  • 代码
  • 总结
  • 参考


代码
    public static void execute() throws IOException {
        StringBuffer requestMessage = new StringBuffer();
        requestMessage.append("GET /add2 HTTP/1.1rn");
        requestMessage.append("cache-control: no-cachern");
        requestMessage.append("Accept: */*rn");
        requestMessage.append("Host: 127.0.0.1:8080rn");
        requestMessage.append("Connection: keep-alivern");
        
        Socket client = new Socket();
        InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1", 8080);
        client.connect(inetSocketAddress, 1000);
        PrintWriter pWriter = new PrintWriter(client.getOutputStream(),true);
        pWriter.println(requestMessage.toString());
        client.close();
    }

http接口使用的springboot

 @GetMapping("/add2")
    public String addUser(){
        System.out.println("小明");
        return "success";
    }
总结

http协议是基于tcp的,当tcp中的数据具有某些特定的格式的时候,就能称之为http协议:比如上文的往socket中写入的数据的第一行: GET /add2 HTTP/1.1
而http协议进行解析时,会对固定格式的数据进行解析,比如:/add2,就会映射到 Controller中的 @GetMapping("/add2")上(框架自动处理好的)

参考

参考地址

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/270090.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号