Java之使用socket连接http接口

Java之使用socket连接http接口


代码

    public static void execute() throws IOException {
        StringBuffer requestMessage = new StringBuffer();
        requestMessage.append("GET /add2 HTTP/1.1\r\n");
        requestMessage.append("cache-control: no-cache\r\n");
        requestMessage.append("Accept: */*\r\n");
        requestMessage.append("Host: 127.0.0.1:8080\r\n");
        requestMessage.append("Connection: keep-alive\r\n");
        
        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")上(框架自动处理好的)

参考

参考地址

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值