<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<直接上代码>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

Person

  1. public class Person {
  2. private String name;
  3. private Integer age;
  4.  
  5. public String getName() {
  6. return name;
  7. }
  8.  
  9. public void setName(String name) {
  10. this.name = name;
  11. }
  12.  
  13. public Integer getAge() {
  14. return age;
  15. }
  16.  
  17. public void setAge(Integer age) {
  18. this.age = age;
  19. }
  20. }

PersonReq

  1. public class PersonReq {
  2. private String name;
  3. private Integer age;
  4.  
  5. public String getName() {
  6. return name;
  7. }
  8.  
  9. public void setName(String name) {
  10. this.name = name;
  11. }
  12.  
  13. public Integer getAge() {
  14. return age;
  15. }
  16.  
  17. public void setAge(Integer age) {
  18. this.age = age;
  19. }
  20. }

DemoService

  1. package com.demo;
  2.  
  3. import org.springframework.stereotype.Service;
  4.  
  5. import java.util.ArrayList;
  6. import java.util.List;
  7.  
  8. @Service
  9. public class DemoService {
  10. /**
  11. * 获取列表
  12. *
  13. * @param personReq 对象参数
  14. * @return
  15. */
  16. public List<Person> personList(PersonReq personReq) {
  17. List<Person> list = new ArrayList<>();
  18. Person person = new Person();
  19. person.setAge(personReq.getAge());
  20. person.setName(personReq.getName());
  21. Person person1 = new Person();
  22. person1.setAge(20);
  23. person1.setName("2诗");
  24. list.add(person);
  25. list.add(person1);
  26. return list;
  27. }
  28. }

DemoController

  1. package com.demo;
  2.  
  3. import com.alibaba.fastjson.JSON;
  4. import org.slf4j.Logger;
  5. import org.slf4j.LoggerFactory;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.web.bind.annotation.RequestBody;
  8. import org.springframework.web.bind.annotation.RequestMapping;
  9. import org.springframework.web.bind.annotation.RestController;
  10.  
  11. import java.util.List;
  12.  
  13. @RestController
  14. @RequestMapping("/demo")
  15. public class DemoController {
  16. private final Logger logger = LoggerFactory.getLogger(this.getClass());
  17. @Autowired
  18. DemoService demo;
  19.  
  20. @RequestMapping("/list")
  21. public List<Person> getPerson(@RequestBody PersonReq personReq) {
  22. List<Person> people = demo.personList(personReq);
  23. logger.info("list:{}", JSON.toJSONString(people));
  24. return people;
  25. }
  26. }

Application

启动项目,然后下一步,外部 就可以开始调接口了

  1. package com;
  2.  
  3. import org.springframework.boot.SpringApplication;
  4. import org.springframework.boot.autoconfigure.SpringBootApplication;
  5. import org.springframework.scheduling.annotation.EnableScheduling;
  6. import springfox.documentation.swagger2.annotations.EnableSwagger2;
  7.  
  8. @EnableScheduling
  9. @EnableSwagger2
  10. @SpringBootApplication
  11. public class Application {
  12. public static void main(String[] args) {
  13. SpringApplication.run(Application.class, args);
  14. }
  15. }

HttpClients

  1. package com.demo;
  2.  
  3. import com.alibaba.fastjson.JSONObject;
  4.  
  5. import java.io.BufferedReader;
  6. import java.io.InputStreamReader;
  7. import java.io.OutputStreamWriter;
  8. import java.io.PrintWriter;
  9. import java.net.HttpURLConnection;
  10. import java.net.URL;
  11.  
  12. /**
  13. * HTTP 工具类
  14. */
  15. public class HttpClients {
  16. /**
  17. * 发送POST请求
  18. *
  19. * @param url 请求URL
  20. * @param param 请求参数
  21. * @return
  22. */
  23. private String sendPost(String url, String param) {
  24.  
  25. return null;
  26. }
  27.  
  28. public static String sendPost(String url, String request, String ContentType) {
  29. String result = "";
  30.  
  31. try {
  32. //存储请求
  33. PrintWriter out;
  34.  
  35. //存储接口返回的response
  36. BufferedReader in;
  37.  
  38. // 获取访问地址
  39. //得到网络访问对象java.net.HttpURLConnection
  40. URL realUrl = new URL(url);
  41.  
  42. //设置请求参数,以流的形式连接
  43. HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
  44.  
  45. //设置http的请求头
  46. conn.setRequestProperty("accept", "*/*");
  47.  
  48. //设置请求的Contenttype
  49. if (ContentType == null || ContentType.equals("")) {
  50. if (isJson(request)) {
  51. conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
  52. } else {
  53. if (url.toLowerCase().contains(".asmx")) {
  54. conn.setRequestProperty("Content-Type", "text/xml;charset=utf-8");
  55. } else {
  56. conn.setRequestProperty("Content-Type", "application/xml;charset=utf-8");
  57. }
  58. }
  59. } else {
  60. conn.setRequestProperty("Content-Type", ContentType);
  61. }
  62.  
  63. //特殊处理:如果是1.0的请求则进一步具体设定setRequestProperty,并对xml格式做优化
  64. if (url.toLowerCase().contains(".asmx")) {
  65. if (url.toLowerCase().contains("datacomparews")) {
  66. conn.setRequestProperty("SOAPAction", "http://tempuri.org/DataTableCompare");
  67. String Xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
  68. "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
  69. "<soap:Body>";
  70. Xml += request.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", "");
  71. Xml += "</soap:Body></soap:Envelope>";
  72. request = Xml;
  73. } else {
  74. String Xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
  75. "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
  76. "<soap:Body><Request xmlns=\"http://tempuri.org/\"><requestXML>" + "<![CDATA[";
  77. Xml += request.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", "");
  78. Xml += "]]></requestXML></Request></soap:Body></soap:Envelope>";
  79. request = Xml;
  80. conn.setRequestProperty("SOAPAction", "http://tempuri.org/Request");
  81. }
  82. }
  83.  
  84. //keep-alive 发出的请求建议服务器端保留连接,这样下次向同一个服务器发请求时可以走同一个连接
  85. conn.setRequestProperty("connection", "Keep-Alive");
  86.  
  87. //设置请求的浏览器相关属性
  88. conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
  89.  
  90. //设定接受的返回流字节码为UTF-8
  91. conn.setRequestProperty("Accept-Charset", "utf-8");
  92. conn.setRequestProperty("Charset", "utf-8");
  93.  
  94. //设置超时时间,如果未设置超时时间,但是访问超时了就会一直卡在这里
  95. conn.setConnectTimeout(50000 * 12);
  96. conn.setReadTimeout(50000 * 12);
  97.  
  98. //设置是否向HttpURLConnection输出,默认为false,发送post请求的不啊必须设置为true
  99. conn.setDoOutput(true);
  100.  
  101. //设置是否从httpUrlConnection读入,默认为true,不设置也可以
  102. conn.setDoInput(true);
  103.  
  104. //处理输入请求 ,设置请求正文,即要提交的数据
  105. out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "utf-8"));
  106.  
  107. // 写入参数到请求中
  108. out.print(request);
  109.  
  110. //flush输出流的缓冲
  111. out.flush();
  112.  
  113. //处理输出接口,远程对象变为可用
  114. in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
  115.  
  116. String line;
  117. while ((line = in.readLine()) != null) {
  118. result += line;
  119. }
  120. } catch (Exception e) {
  121. result = e.getMessage();
  122. e.printStackTrace();
  123. }
  124. return result;
  125. }
  126.  
  127. /**
  128. * 判断字符串是不是json格式
  129. *
  130. * @param request
  131. * @return
  132. */
  133. private static boolean isJson(String request) {
  134. try {
  135. JSONObject.parseObject(request);
  136. return true;
  137. } catch (Exception e) {
  138. return false;
  139. }
  140. }
  141. }
  1. Demo1Controller
  1. package com.demo;
  2.  
  3. import com.alibaba.fastjson.JSON;
  4. import org.slf4j.Logger;
  5. import org.slf4j.LoggerFactory;
  6. import org.springframework.web.bind.annotation.RequestMapping;
  7. import org.springframework.web.bind.annotation.RestController;
  8.  
  9. @RestController
  10. @RequestMapping("/demo1")
  11. public class Demo1Controller {
  12. private static final Logger logger = LoggerFactory.getLogger(Demo1Controller.class);
  13.  
  14. @RequestMapping("/list")
  15. public String getPerson1() {
  16. PersonReq personReq = new PersonReq();
  17. personReq.setAge(10);
  18. personReq.setName("1诗");
  19. String url = "http://localhost:8080/demo/list";
  20. String result = HttpClients.sendPost(url, JSON.toJSONString(personReq), "");
  21. logger.info(" getPerson1 list:{}", result);
  22. return result;
  23. }

  24. //mian方法测试
  25. public static void main(String[] args) {
  26. PersonReq personReq = new PersonReq();
  27. personReq.setAge(10);
  28. personReq.setName("1诗");
  29. String url = "http://localhost:8080/demo/list";
  30. String result = HttpClients.sendPost(url, JSON.toJSONString(personReq), "");
  31. logger.info("result:{}", result);
  32. }
  33. }

<<<<<<<<<<<<<<<OK>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

Java POST请求案例的更多相关文章

  1. Post的请求案例

    1.简单的post请求案例 $.post(rootPath+"/jasframework/loginLog/getStatisticsInfoByUserId.do",functi ...

  2. Java HTTP请求

    注意:java  http请求要放在 try catch里面,该过程是一个阻塞过程,所以需要新建一个线程进行处理 try { HttpPost request = new HttpPost(URL); ...

  3. java读取请求中body数据

    java读取请求中body数据 /** * 获取request中body数据 * * @author lifq * * 2017年2月24日 下午2:29:06 * @throws IOExcepti ...

  4. JAVA之旅(三十二)——JAVA网络请求,IP地址,TCP/UDP通讯协议概述,Socket,UDP传输,多线程UDP聊天应用

    JAVA之旅(三十二)--JAVA网络请求,IP地址,TCP/UDP通讯协议概述,Socket,UDP传输,多线程UDP聊天应用 GUI写到一半电脑系统挂了,也就算了,最多GUI还有一个提示框和实例, ...

  5. Java过滤器处理Ajax请求,Java拦截器处理Ajax请求,java 判断请求是不是ajax请求

    Java过滤器处理Ajax请求,Java拦截器处理Ajax请求,java 判断请求是不是ajax请求   Java过滤器处理Ajax请求,Java拦截器处理Ajax请求,拦截器Ajax请求 java ...

  6. 解决Fiddler不能监听Java HttpURLConnection请求的方法

    在默认情况下,Fiddler不能监听Java HttpURLConnection请求.究其原因,Java的网络通信协议栈可能浏览器的通信协议栈略有区别,Fiddler监听Http请求的原理是 在应用程 ...

  7. 前端笔记之微信小程序(三)GET请求案例&文件上传和相册API&配置https

    一.信息流小程序-GET请求案例 1.1服务端接口开发 一定要养成接口的意识,前端单打独斗出不来任何效果,必须有接口配合,写一个带有分页.关键词查询的接口: 分页接口:http://127.0.0.1 ...

  8. 使用Fiddler监听java HttpURLConnection请求

    使用Fiddler监听java HttpURLConnection请求

  9. java判断请求是否ajax异步请求

    java判断请求是否ajax异步请求   解决方法: if (request.getHeader("x-requested-with") != null && re ...

随机推荐

  1. Shareplex搭建步骤(rman)

    实施例:rman/BCV 环境准备 splex软件上传 源端: #mkdir /quest #chmod -R 755 /quest #chown -R oracle:oinstall /quest ...

  2. Vue+Java+Base64实现条码解析

    前端部分(Vue + Vant) 引入Vant.使用Vant中的Uploader组件上传文件(支持手机拍照) import Vue from 'vue'; import { Uploader } fr ...

  3. 搜索引擎学习(二)Lucene创建索引

    PS:需要用到的jar包: 代码实现 1.工程结构 2.设置工程依赖的jar包 3.代码实现 /** * Lucene入门 * 创建索引 */ public class CreateIndex { / ...

  4. 从 LRU Cache 带你看面试的本质

    前言 大家好,这里是<齐姐聊算法>系列之 LRU 问题. 在讲这道题之前,我想先聊聊「技术面试究竟是在考什么」这个问题. 技术面试究竟在考什么 在人人都知道刷题的今天,面试官也都知道大家会 ...

  5. 适配器(adapter)与fragment之间、fragment与activity之间的通信问题

    一.适配器(adapter)与fragment之间通信 通过本地广播进行通信 步骤如下 在adapter中代码 声明本地广播管理 private LocalBroadcastManager local ...

  6. 零基础小白必看篇:从0到1构建Python Web框架

    造轮子是最好的一种学习方式,本文尝试从0开始造个Python Web框架的轮子,我称它为ToyWebF. 本文操作环境为:MacOS,文中涉及的命令,请根据自己的系统进行替换. ToyWebF的简单特 ...

  7. makefile实验四 编译本地的源文件 + 变量的高级主题一

    <一>编译本地的源文件 + 变量的模式替换    实验代码 root@ubuntu:~/Makefile_Test/5make_test# vim makefile target := t ...

  8. Spring Cloud系列(三):Eureka源码解析之服务端

    一.自动装配 1.根据自动装配原理(详见:Spring Boot系列(二):Spring Boot自动装配原理解析),找到spring-cloud-starter-netflix-eureka-ser ...

  9. C语言中 malloc

    参考:https://blog.csdn.net/kokodudu/article/details/11760863 一.malloc()和free()的基本概念以及基本用法: 1.函数原型及说明: ...

  10. MYSQL账户是否不允许远程连接。如果无法连接可以尝试以下方法:

    mysql账户是否不允许远程连接.如果无法连接可以尝试以下方法: mysql -u root -p //登录MySQL mysql> GRANT ALL PRIVILEGES ON *.* TO ...