Java POST请求案例
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<直接上代码>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Person
public class Person {
private String name;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
PersonReq
public class PersonReq {
private String name;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
DemoService
package com.demo; import org.springframework.stereotype.Service; import java.util.ArrayList;
import java.util.List; @Service
public class DemoService {
/**
* 获取列表
*
* @param personReq 对象参数
* @return
*/
public List<Person> personList(PersonReq personReq) {
List<Person> list = new ArrayList<>();
Person person = new Person();
person.setAge(personReq.getAge());
person.setName(personReq.getName());
Person person1 = new Person();
person1.setAge(20);
person1.setName("2诗");
list.add(person);
list.add(person1);
return list;
}
}
DemoController
package com.demo; import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController
@RequestMapping("/demo")
public class DemoController {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
DemoService demo; @RequestMapping("/list")
public List<Person> getPerson(@RequestBody PersonReq personReq) {
List<Person> people = demo.personList(personReq);
logger.info("list:{}", JSON.toJSONString(people));
return people;
}
}
Application
启动项目,然后下一步,外部 就可以开始调接口了
package com; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
import springfox.documentation.swagger2.annotations.EnableSwagger2; @EnableScheduling
@EnableSwagger2
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
HttpClients
package com.demo; import com.alibaba.fastjson.JSONObject; import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL; /**
* HTTP 工具类
*/
public class HttpClients {
/**
* 发送POST请求
*
* @param url 请求URL
* @param param 请求参数
* @return
*/
private String sendPost(String url, String param) { return null;
} public static String sendPost(String url, String request, String ContentType) {
String result = ""; try {
//存储请求
PrintWriter out; //存储接口返回的response
BufferedReader in; // 获取访问地址
//得到网络访问对象java.net.HttpURLConnection
URL realUrl = new URL(url); //设置请求参数,以流的形式连接
HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection(); //设置http的请求头
conn.setRequestProperty("accept", "*/*"); //设置请求的Contenttype
if (ContentType == null || ContentType.equals("")) {
if (isJson(request)) {
conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
} else {
if (url.toLowerCase().contains(".asmx")) {
conn.setRequestProperty("Content-Type", "text/xml;charset=utf-8");
} else {
conn.setRequestProperty("Content-Type", "application/xml;charset=utf-8");
}
}
} else {
conn.setRequestProperty("Content-Type", ContentType);
} //特殊处理:如果是1.0的请求则进一步具体设定setRequestProperty,并对xml格式做优化
if (url.toLowerCase().contains(".asmx")) {
if (url.toLowerCase().contains("datacomparews")) {
conn.setRequestProperty("SOAPAction", "http://tempuri.org/DataTableCompare");
String Xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<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/\">" +
"<soap:Body>";
Xml += request.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", "");
Xml += "</soap:Body></soap:Envelope>";
request = Xml;
} else {
String Xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<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/\">" +
"<soap:Body><Request xmlns=\"http://tempuri.org/\"><requestXML>" + "<![CDATA[";
Xml += request.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", "");
Xml += "]]></requestXML></Request></soap:Body></soap:Envelope>";
request = Xml;
conn.setRequestProperty("SOAPAction", "http://tempuri.org/Request");
}
} //keep-alive 发出的请求建议服务器端保留连接,这样下次向同一个服务器发请求时可以走同一个连接
conn.setRequestProperty("connection", "Keep-Alive"); //设置请求的浏览器相关属性
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); //设定接受的返回流字节码为UTF-8
conn.setRequestProperty("Accept-Charset", "utf-8");
conn.setRequestProperty("Charset", "utf-8"); //设置超时时间,如果未设置超时时间,但是访问超时了就会一直卡在这里
conn.setConnectTimeout(50000 * 12);
conn.setReadTimeout(50000 * 12); //设置是否向HttpURLConnection输出,默认为false,发送post请求的不啊必须设置为true
conn.setDoOutput(true); //设置是否从httpUrlConnection读入,默认为true,不设置也可以
conn.setDoInput(true); //处理输入请求 ,设置请求正文,即要提交的数据
out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "utf-8")); // 写入参数到请求中
out.print(request); //flush输出流的缓冲
out.flush(); //处理输出接口,远程对象变为可用
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8")); String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
result = e.getMessage();
e.printStackTrace();
}
return result;
} /**
* 判断字符串是不是json格式
*
* @param request
* @return
*/
private static boolean isJson(String request) {
try {
JSONObject.parseObject(request);
return true;
} catch (Exception e) {
return false;
}
}
}
Demo1Controller
package com.demo; import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; @RestController
@RequestMapping("/demo1")
public class Demo1Controller {
private static final Logger logger = LoggerFactory.getLogger(Demo1Controller.class); @RequestMapping("/list")
public String getPerson1() {
PersonReq personReq = new PersonReq();
personReq.setAge(10);
personReq.setName("1诗");
String url = "http://localhost:8080/demo/list";
String result = HttpClients.sendPost(url, JSON.toJSONString(personReq), "");
logger.info(" getPerson1 list:{}", result);
return result;
}
//mian方法测试
public static void main(String[] args) {
PersonReq personReq = new PersonReq();
personReq.setAge(10);
personReq.setName("1诗");
String url = "http://localhost:8080/demo/list";
String result = HttpClients.sendPost(url, JSON.toJSONString(personReq), "");
logger.info("result:{}", result);
}
}

<<<<<<<<<<<<<<<OK>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Java POST请求案例的更多相关文章
- Post的请求案例
1.简单的post请求案例 $.post(rootPath+"/jasframework/loginLog/getStatisticsInfoByUserId.do",functi ...
- Java HTTP请求
注意:java http请求要放在 try catch里面,该过程是一个阻塞过程,所以需要新建一个线程进行处理 try { HttpPost request = new HttpPost(URL); ...
- java读取请求中body数据
java读取请求中body数据 /** * 获取request中body数据 * * @author lifq * * 2017年2月24日 下午2:29:06 * @throws IOExcepti ...
- JAVA之旅(三十二)——JAVA网络请求,IP地址,TCP/UDP通讯协议概述,Socket,UDP传输,多线程UDP聊天应用
JAVA之旅(三十二)--JAVA网络请求,IP地址,TCP/UDP通讯协议概述,Socket,UDP传输,多线程UDP聊天应用 GUI写到一半电脑系统挂了,也就算了,最多GUI还有一个提示框和实例, ...
- Java过滤器处理Ajax请求,Java拦截器处理Ajax请求,java 判断请求是不是ajax请求
Java过滤器处理Ajax请求,Java拦截器处理Ajax请求,java 判断请求是不是ajax请求 Java过滤器处理Ajax请求,Java拦截器处理Ajax请求,拦截器Ajax请求 java ...
- 解决Fiddler不能监听Java HttpURLConnection请求的方法
在默认情况下,Fiddler不能监听Java HttpURLConnection请求.究其原因,Java的网络通信协议栈可能浏览器的通信协议栈略有区别,Fiddler监听Http请求的原理是 在应用程 ...
- 前端笔记之微信小程序(三)GET请求案例&文件上传和相册API&配置https
一.信息流小程序-GET请求案例 1.1服务端接口开发 一定要养成接口的意识,前端单打独斗出不来任何效果,必须有接口配合,写一个带有分页.关键词查询的接口: 分页接口:http://127.0.0.1 ...
- 使用Fiddler监听java HttpURLConnection请求
使用Fiddler监听java HttpURLConnection请求
- java判断请求是否ajax异步请求
java判断请求是否ajax异步请求 解决方法: if (request.getHeader("x-requested-with") != null && re ...
随机推荐
- SQL中只要用到聚合函数就一定要用到group by 吗?
1.当聚集函数和非聚集函数出现在一起时,需要将非聚集函数进行group by2.当只做聚集函数查询时候,就不需要进行分组了.
- day54:django:锁和事务&Ajax&中间件Middleware
目录 1.ORM中的锁和事务 2.Ajax 3.中间件:Middleware 3.1 什么是中间件? 3.2 django请求的生命周期 3.3 中间件可以定义的5个方法 3.4 自定义中间件的流程 ...
- 2020华为杯数学建模B题-RON建模 赛后总结与分析
好久好久没有写博客了...挺累的,从二月份开始找暑期实习,接着在进行暑期实习,然后马不停蹄地进行秋招,现在总算结束实习,前两天又参加了华为杯数学建模竞赛,感觉接下来就会很轻松了,希望能好好休息休息.这 ...
- 获取NX一组属性
NX中的属性是可以分组的,有时我们想获取某一个组下的所有属性,但是NX封装的接口不够好用,因此在此基础上,我封装了一个,供大家参考: 1 //属性值是字符串类型,obj对象tag,category组名 ...
- 刷题[BJDCTF 2nd]简单注入
解题思路 打开发现登陆框,随机输入一些,发现有waf,然后回显都是同样的字符串.fuzz一波,发现禁了挺多东西的. select union 等 这里猜测是布尔盲注,错误的话显示的是:You konw ...
- noSql 的应用场景简述
选型一定要结合实际情况而不是照本宣科,比如: 企业发展之初,明明一个关系型数据库就能搞定且支撑一年的架构,搞一套大而全的技术方案出来 有一些数据条件查询多,更适合使用ElasticSearch做存储降 ...
- python安装和首次使用
安装: 1.安装python环境: 首先打开python官网,下载配置环境:www.python.org 点击上方downloads, 根据系统选择python环境下载 找到 windows x86- ...
- 安装Ubuntu虚拟机
centos已经满足不了我了,这里就装了个虚拟机,等有钱了再单配台单系统的Linux主机. 一.下载Ubuntu的ISO文件 用国内的网易镜像站点 进去点个16.04.6,然后下个64位的.iso就好 ...
- ios7.1发布企业证书测试包的问题
关于升级了ios7.1之后发布企业版证书的测试包不能下载的问题,这个苹果也挺坑的,什么都不说,也不警告一下,直接就不能用了 用xcode的organizer里面的console里发现安装的时候提示这个 ...
- c#后台代码请求访问api接口
前言:最近公司项目与外部api接口对接较多 ,写下自己的代码总结.介绍两种访问方式(HttpClient.HttpWebRequest) 一.HttpWebRequest 访问Api private ...