admin 管理员组

文章数量: 1184232

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")上(框架自动处理好的)

参考

参考地址

本文标签: Java之使用socket连接http接口