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 ...
随机推荐
- 关于多个 Kubernetes 集群指标的采集操作
简介 在使用观测云期间,有时需要针对一个工作空间接入多个 Kubernetes 集群指标,通过观测云提供的全局 Tag 的方式来进行区分,大大提高了效率.下面是我总结的操作步骤. 当集群中只有一个采集 ...
- 使用@Param标识参数
可以通过@Param注解标识mapper接口中的方法参数 此时,会将这些参数放在map集合中,以@Param注解的value属性值为键,以参数为值: 以 param1,param2...为键,以参数为 ...
- http://localhost:8282/user/findsomeuser[object%20Object]
查看vue中的方法的访问路径是否填写正确. 后端:
- cmd复制移动合并文件
1.单文件复制: (1)把c:\1.txt复制到c:\2\文件夹下 copy c:\1.txt c:\2\ (2)把c:\1.txt复制到c:\1\文件夹下,并把它修改为777.docx copy c ...
- 十、Pod的init containers
Pod 的 init Containers Pod 我们可以分为两类,一种属于自主式 Pod ,还有一种属于控制器管理的 Pod . 一.Pod 的 initContainers 基本概念: Pod ...
- (数据科学学习手札146)geopandas中拓扑非法问题的发现、诊断与修复
本文示例代码已上传至我的Github仓库https://github.com/CNFeffery/DataScienceStudyNotes 1 简介 大家好我是费老师,geopandas作为在Pyt ...
- Codeforces Round #820 (Div. 3) A-G
比赛链接 A 题解 知识点:模拟 时间复杂度 \(O(1)\) 空间复杂度 \(O(1)\) 代码 #include <bits/stdc++.h> #define ll long lon ...
- CF815D
模拟赛遇到的题目. 看各位大佬的做法都不是很懂,于是自己一通乱搞搞出来了. 题意 翻译清楚的不能再清楚了 做法 为了方便叙述,我们将每个给出的三元组表示成 \((a_i,b_i,c_i)\),所选的三 ...
- KeeWiDB的高性能修炼之路:架构篇
数据也有冷热之分,你知道吗? 根据访问的频率的高低可将数据分为热数据和冷数据,访问频率高的则为热数据,低为冷数据.如果热.冷数据不区分,一并存储,显然不科学.将冷数据也存储在昂贵的内存中,那么你想,成 ...
- Linux 挂载Windows共享文件夹和NAS存储
summary: [Linux 挂载共享存储] 概述 将Windows共享文件夹和NAS存储挂载至Linux. Linux系统环境:CentOS 挂载共享存储 查看外部主机共享了哪些目录 smbcli ...