Http请求接口
方法一、使用springboot框间自带的Http的工具类RestTemplate。
RestTemplate为springframework中自带的处理Http的工具类。
具体用法
请求的接口
@RestController
@RequestMapping("/index")
public class MyController {
@PostMapping("/testPost")
public Map<String, Object> testPost(@RequestBody Map map) {
Map<String, Object> mm = new HashMap<>();
mm.put("学号", map.get("sno"));
mm.put("姓名", map.get("sname"));
mm.put("年龄", map.get("age"));
mm.put("性别", map.get("sex"));
mm.put("班级", map.get("sclass"));
return mm;
}
@GetMapping("/testGet")
public Student testGet(@RequestParam String sno,
@RequestParam String sname,
@RequestParam String age,
@RequestParam String sex,
@RequestParam String sclass) {
Student student = new Student(Integer.parseInt(sno), sname, Integer.parseInt(age), sex, sclass);
return student;
}
}
Get和Post请求
@Test
public void testExchange_post() {
Student student = new Student(20160004, "李四", 20, "男", "2016222");
RestTemplate restTemplate = new RestTemplate();
HttpHeaders httpHeaders = new HttpHeaders();
//headerName必须是英文,headerValue可以有中文
//请求头会封装一些像token这些信息,用于作为调接口的鉴权
httpHeaders.add("studentInfo", "个人信息");
HttpEntity<Student> httpEntity = new HttpEntity<>(student, httpHeaders);
System.out.println("httpEntity的请求头为:" + httpEntity.getHeaders());
System.out.println("httpEntity的请求体为:" + httpEntity.getBody());
ResponseEntity<Map> responseEntity = restTemplate.exchange("http://localhost:8080/index/testPost", HttpMethod.POST, httpEntity, Map.class);
System.out.println("返回的请求头为:" + responseEntity.getHeaders());
System.out.println("返回的请求体为:" + responseEntity.getBody());
}
@Test
public void testExchange_get() {
Student student = new Student(20160004, "李四", 20, "男", "2016222");
RestTemplate restTemplate = new RestTemplate();
HttpHeaders httpHeaders = new HttpHeaders();
//headerName必须是英文,headerValue可以有中文
httpHeaders.add("cookie", "cookie");
HttpEntity<Student> httpEntity = new HttpEntity<>(null, httpHeaders);
System.out.println("httpEntity的请求头为:" + httpEntity.getHeaders());
System.out.println("httpEntity的请求体为:" + httpEntity.getBody());
Map<String, Object> map = new HashMap<>();
ResponseEntity<Student> responseEntity = restTemplate.
exchange("http://localhost:8080/index/testGet?sno={sno}&sname={sname}&age={age}&sex={sex}&sclass={sclass}",
HttpMethod.GET, httpEntity, Student.class, student.getSno(), student.getSname(), student.getAge(), student.getSex(), student.getSclass());
System.out.println("返回的请求头为:" + responseEntity.getHeaders());
System.out.println("返回的请求体为:" + responseEntity.getBody());
}
方法二、使用apache的httpclient工具类
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.78</version>
</dependency>
@Test
public void testHttpClient_get() throws URISyntaxException, IOException {
// 获得Http客户端
HttpClient httpClient = HttpClientBuilder.create().build();
Student student = new Student(20160004, "李四", 20, "男", "2016222");
// 将参数放入键值对类NameValuePair中,再放入集合中
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("sno", String.valueOf(student.getSno())));
params.add(new BasicNameValuePair("sname", student.getSname()));
params.add(new BasicNameValuePair("age", String.valueOf(student.getAge())));
params.add(new BasicNameValuePair("sex", student.getSex()));
params.add(new BasicNameValuePair("sclass", student.getSclass()));
URI uri = new URIBuilder().setScheme("http").setHost("localhost")
.setPort(8080).setPath("/index/testGet")
.setParameters(params).build();
// 创建Get请求
HttpGet httpGet = new HttpGet(uri);
// 响应模型
HttpResponse response = null;
try {
// 配置信息
RequestConfig requestConfig = RequestConfig.custom()
// 设置连接超时时间(单位毫秒)
.setConnectTimeout(5000)
// 设置请求超时时间(单位毫秒)
.setConnectionRequestTimeout(5000)
// socket读写超时时间(单位毫秒)
.setSocketTimeout(5000)
// 设置是否允许重定向(默认为true)
.setRedirectsEnabled(true).build();
// 将上面的配置信息 运用到这个Get请求里
httpGet.setConfig(requestConfig);
// 由客户端执行(发送)Get请求
response = httpClient.execute(httpGet);
// 从响应模型中获取响应实体
org.apache.http.HttpEntity responseEntity = response.getEntity();
System.out.println("响应状态为:" + response.getStatusLine());
if (responseEntity != null) {
System.out.println("响应内容长度为:" + responseEntity.getContentLength());
System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));
}
} finally {
// try {
// // 释放资源
// if (httpClient != null) {
// httpClient.close();
// }
// if (response != null) {
// response.close();
// }
// } catch (IOException e) {
// e.printStackTrace();
// }
//CloseableHttpClient HttpClient HttpResponse HttpServletResponse
}
}
@Test
public void testHttpClient_post() throws URISyntaxException, IOException {
// 获得Http客户端
HttpClient httpClient = HttpClientBuilder.create().build();
// 创建Post请求
HttpPost httpPost = new HttpPost("http://localhost:8080/index/testPost");
Student student = new Student(20160004, "李四", 20, "男", "2016222");
// 我这里利用阿里的fastjson,将Object转换为json字符串;
// (需要导入com.alibaba.fastjson.JSON包)
String jsonString = JSON.toJSONString(student);
StringEntity entity = new StringEntity(jsonString, "UTF-8");
// post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
httpPost.setEntity(entity);
httpPost.setHeader("Content-Type", "application/json;charset=utf8");
// 响应模型
HttpResponse response = null;
HttpServletResponse httpServletResponse = null;
try {
// 由客户端执行(发送)Post请求
response = httpClient.execute(httpPost);
// 从响应模型中获取响应实体
org.apache.http.HttpEntity responseEntity = response.getEntity();
System.out.println("响应状态为:" + response.getStatusLine());
if (responseEntity != null) {
System.out.println("响应内容长度为:" + responseEntity.getContentLength());
System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// try {
// // 释放资源
// if (httpClient != null) {
// httpClient.close();
// }
// if (response != null) {
// response.close();
// }
// } catch (IOException e) {
// e.printStackTrace();
// }
}
}
参考资料
Http请求接口的更多相关文章
- 项目二(业务GO)——跨域上传图片(请求接口)
之前,就听过“跨域上传”图片的问题,只是疏于研究,也就一再搁置,直至今天再次遇见这个不能避免的“坑”,才不得不思考一下,怎么“跨域上传”图片或者文件? 问题来源: 何为“跨域”? ——就是给你一个接口 ...
- iOS开发-网络-合理封装请求接口
概述 如今大多App都会与网络打交道,作为开发者,合理的对网络后台请求接口进行封装十分重要.本文要介绍的就是一种常见的采用回调函数(方法)的网络接口封装,也算的是一种构架吧. 这个构架主要的idea是 ...
- webServices 使用GET请求接口方法
webServices 若要使用GET请求接口方法在Web.config 下添加这段 <webServices> <protocols> <add ...
- 使用fiddler模拟重复请求接口
使用fiddler模拟重复请求接口 重复请求某个接口,比如评论一条,这样点击多次就可以造多个评论数据
- axios请求接口的踩坑之路
1.跨域问题除了前端安装插件还需要后端php设置,设置如下 Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, ...
- 一个vue请求接口渲染页面的例子
new Vue({ el:'#bodylist', data: { list: [ { "type_id": "1", "type_name" ...
- 使用ajax请求接口,跨域后cookie无法设置,全局配置ajax;及使用axios跨域后cookie无法设置,全局配置axios
问题一: 使用ajax/axios跨域请求接口,后端放行了,能够正常获取数据,但是cookie设置不进去,后端登录session判断失效 ajax解决办法: //设置ajax属性 crossDomai ...
- Retrofit Token过期 重新请求Token再去请求接口
需求是这样的:请求接口A -- 服务器返回数据Token过期或失效 -- 重新请求Token并设置 -- 再去请求接口A 刚解决了这个问题,趁热打铁,写个博客记录一下:这个Token是添加到请求头里 ...
- C# 动态创建SQL数据库(二) 在.net core web项目中生成二维码 后台Post/Get 请求接口 方式 WebForm 页面ajax 请求后台页面 方法 实现输入框小数多 自动进位展示,编辑时实际值不变 快速掌握Gif动态图实现代码 C#处理和对接HTTP接口请求
C# 动态创建SQL数据库(二) 使用Entity Framework 创建数据库与表 前面文章有说到使用SQL语句动态创建数据库与数据表,这次直接使用Entriy Framwork 的ORM对象关 ...
- thinkphp5.0 CURL用post请求接口数据
//测试 请求接口 public function index(){ $arr = array('a'=>'555','b'=>56454564); $data=$this->pos ...
随机推荐
- python实现给定K个字符数组,从这k个字符数组中任意取一个字符串,按顺序拼接,列出所有可能的字符串组合结果!
题目描述:给定K个字符数组,从这k个字符数组中任意取一个字符串,按顺序拼接,列出所有可能的字符串组合结果! 样例: input:[["a","b"," ...
- 程序员便于开发的一些工具、网站、App。
http://www.kancloud.cn 关于文档,各种技术,框架的学习指南,API文档搜索方便. https://leetcode.com/ 程序员刷题面试网站,无聊的时候可以做一做.
- 京东云TiDB SQL优化的最佳实践
京东云TiDB SQL层的背景介绍 从总体上概括 TiDB 和 MySQL 兼容策略,如下表: SQL层的架构 用户的 SQL 请求会直接或者通过 Load Balancer 发送到 京东云TiDB ...
- 齐博软件 著名的老牌CMS开源系统 X1.0基于thinkphp开发的高性能免费开源PHP开放平台齐博x1.0基于thinkphp框架开发的高性能免费开源系统 主推圈子 论坛 预定拼团分销商城模块
齐博X1--标签变量大全 1.网站名称: {$webdb.webname} 2.网址: {$webdb[www_url]} {:get_url('home')} 3.网站SEO关键词: 首页:{$we ...
- vue3中$attrs的变化与inheritAttrs的使用
在vue3中的$attrs的变化 $listeners已被删除合并到$attrs中. $attrs现在包括class和style属性. 也就是说在vue3中$listeners不存在了.vue2中$l ...
- XPAND模板语言语法1.0
XPAND模板语言语法1.0 Xpand模板语言一般写在以.xpt为结尾的文本文件中 ,以"« »" 作为开头和结尾 .Xpand语言主要包括以下几个标签: «IMPORT», ...
- 九、docker swarm主机编排
一. 什么是Docker Swarm Swarm 是 Docker 公司推出的用来管理 docker 集群的平台,几乎全部用GO语言来完成的开发的,代码开源在https://github.com/do ...
- ThreadPoolExecutor BlockingQueue讲解
有四种常用阻塞队列策略: 1.直接拒绝:(Direct Handoffs) 一个好的工作队列应该是不缓存任务,而是直接交给线程处理,就如SynchronousQueue一样.一个任务将会入队失败,如果 ...
- 机器学习中in-domine, out-domine的区别
in-domine 为域内数据,即为训练模型时使用的数据: out-domine 为域外数据,即为检验模型时使用的数据.
- 最新的ZooKeeper GUI
Zookeeper 是一个分布式的.开源的程序协调服务,是 hadoop 项目下的一个子项目.他提供的主要功 能包括:配置管理.名字服务.分布式锁.集群管理. 平时用zkCli.sh进行管理不免有点不 ...