socket 发送http请求
Posted Java璐到底
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了socket 发送http请求相关的知识,希望对你有一定的参考价值。
发送端: import java.io.*; import java.net.Socket; import java.net.UnknownHostException; public class MySocketHttp { public static void main(String[ ] args) throws UnknownHostException, IOException { String host = "127.0.0.1"; int port = 8008; Socket socket = new Socket(host, port); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); StringBuffer sb = new StringBuffer(); //请求的连接地址 sb.append("POST /hello HTTP/1.1\\r\\n") .append("Host:"+ host + "\\r\\n") .append("Content-Type:application/x-www-form-urlencoded\\r\\n") .append("Content-Length:11\\r\\n")//11 这个数值是看底下内容的长度的 即多少个字符 .append("\\r\\n") .append("id=01234567\\r\\n"); //内容 // System.out.println(sb); out.write(sb.toString()); out.flush(); //打印响应 String line = ""; while((line = in.readLine()) != null) { System.out.println(line); } out.close(); socket.close(); } } 接收端:
@RestController public class FilerController { @PostMapping("hello") public String Hello(HttpServletRequest request, HttpServletResponse response){ try { //接收请求参数 InputStreamReader reader=new InputStreamReader(request.getInputStream()); BufferedReader buffer=new BufferedReader(reader); String data=buffer.readLine(); System.out.println("传入参数:"+data); //头部信息 //String header=request.getHeader("headerdata"); //System.out.println(header); //向客户端发送数据 /* response.setContentType("text/javascript"); Student stu=new Student("liss","44"); Gson json=new Gson(); String jString=json.toJson(stu); PrintWriter out=response.getWriter(); out.write(jString);*/ } catch (IOException e) { e.printStackTrace(); } return "hello word"; } }
以上是关于socket 发送http请求的主要内容,如果未能解决你的问题,请参考以下文章