当前位置:   article > 正文

SpringBoot @PostMapping接收HTTP 请求的流数据方式_springboot post+流

springboot post+流
  1. @PostMapping("/test")
  2. public String pushMessage(@RequestBody byte[] data) throws Exception {
  3. String json = URLDecoder.decode(new String(data, DEFAULT_CHARSET), DEFAULT_CHARSET);
  4. log.info(">>> 接收CP推送的消息:{}", json);
  5. JSONObject jsonObject = JacksonUtils.jsonToBean(json, JSONObject.class);

         System.out.println(jsonObject.get("key"));

         return “success”

}

---

Client 请求

  1. try {
  2. //创建连接
  3. URL url = new URL(ADD_URL);
  4. HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  5. connection.setDoOutput(true);
  6. connection.setDoInput(true);
  7. connection.setRequestMethod("POST");
  8. connection.setUseCaches(false);
  9. connection.setInstanceFollowRedirects(true);
  10. //application/x-javascript
  11. //text/xml->xml数据
  12. //application/x-javascript->json对象
  13. //application/x-www-form-urlencoded->表单数据
  14. //application/json;charset=utf-8 -> json数据
  15. connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
  16. connection.setRequestProperty("accept", "*/*");
  17. connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
  18. connection.connect();
  19. //POST请求
  20. DataOutputStream out = new DataOutputStream(connection.getOutputStream());
  21. JSONObject data = new JSONObject();
  22. data.element("key", "这是一条测试数据");
  23. out.writeBytes(data.toString());
  24. out.flush();
  25. out.close();
  26. //读取响应
  27. BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
  28. String lines;
  29. StringBuffer sb = new StringBuffer("");
  30. while ((lines = reader.readLine()) != null) {
  31. lines = new String(lines.getBytes(), "utf-8");
  32. sb.append(lines);
  33. }
  34. System.out.println(sb);
  35. reader.close();
  36. // 断开连接
  37. connection.disconnect();
  38. } catch (MalformedURLException e) {
  39. // TODO Auto-generated catch block
  40. e.printStackTrace();
  41. } catch (UnsupportedEncodingException e) {
  42. // TODO Auto-generated catch block
  43. e.printStackTrace();
  44. } catch (IOException e) {
  45. // TODO Auto-generated catch block
  46. e.printStackTrace();
  47. }

 如果该文章对您有帮助请帮忙 点赞 或 打赏

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/80493
推荐阅读
相关标签
  

闽ICP备14008679号