方法一、使用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请求接口的更多相关文章

  1. 项目二(业务GO)——跨域上传图片(请求接口)

    之前,就听过“跨域上传”图片的问题,只是疏于研究,也就一再搁置,直至今天再次遇见这个不能避免的“坑”,才不得不思考一下,怎么“跨域上传”图片或者文件? 问题来源: 何为“跨域”? ——就是给你一个接口 ...

  2. iOS开发-网络-合理封装请求接口

    概述 如今大多App都会与网络打交道,作为开发者,合理的对网络后台请求接口进行封装十分重要.本文要介绍的就是一种常见的采用回调函数(方法)的网络接口封装,也算的是一种构架吧. 这个构架主要的idea是 ...

  3. webServices 使用GET请求接口方法

    webServices  若要使用GET请求接口方法在Web.config 下添加这段 <webServices>     <protocols>       <add  ...

  4. 使用fiddler模拟重复请求接口

    使用fiddler模拟重复请求接口 重复请求某个接口,比如评论一条,这样点击多次就可以造多个评论数据

  5. axios请求接口的踩坑之路

    1.跨域问题除了前端安装插件还需要后端php设置,设置如下 Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, ...

  6. 一个vue请求接口渲染页面的例子

    new Vue({ el:'#bodylist', data: { list: [ { "type_id": "1", "type_name" ...

  7. 使用ajax请求接口,跨域后cookie无法设置,全局配置ajax;及使用axios跨域后cookie无法设置,全局配置axios

    问题一: 使用ajax/axios跨域请求接口,后端放行了,能够正常获取数据,但是cookie设置不进去,后端登录session判断失效 ajax解决办法: //设置ajax属性 crossDomai ...

  8. Retrofit Token过期 重新请求Token再去请求接口

    需求是这样的:请求接口A -- 服务器返回数据Token过期或失效  -- 重新请求Token并设置 -- 再去请求接口A 刚解决了这个问题,趁热打铁,写个博客记录一下:这个Token是添加到请求头里 ...

  9. C# 动态创建SQL数据库(二) 在.net core web项目中生成二维码 后台Post/Get 请求接口 方式 WebForm 页面ajax 请求后台页面 方法 实现输入框小数多 自动进位展示,编辑时实际值不变 快速掌握Gif动态图实现代码 C#处理和对接HTTP接口请求

    C# 动态创建SQL数据库(二) 使用Entity Framework  创建数据库与表 前面文章有说到使用SQL语句动态创建数据库与数据表,这次直接使用Entriy Framwork 的ORM对象关 ...

  10. thinkphp5.0 CURL用post请求接口数据

    //测试 请求接口 public function index(){ $arr = array('a'=>'555','b'=>56454564); $data=$this->pos ...

随机推荐

  1. CentOS 7.9 安装 MySQL 5.7.35

    CentOS 7.9 安装 MySQL 5.7.35 1 下载地址:https://downloads.mysql.com/archives/community/ 2 mysql5.7.35 安装包上 ...

  2. git(新)

    Git仓库的工作分区 工作区到暂存区的操作 git init :在当前文件夹创建一个文档库,自动产生一个master分支.当当前文件夹已有文档库时,不会再次创建也不会修改,只会将隐藏的.git文件夹显 ...

  3. 基于QT和C++实现的翻金币游戏

    基于QT和C++的翻金币游戏 声明: QT翻金币项目可以说是每个新学QT的同学都会去写的一个项目,网上的源码也很多,我也是最近刚开始学QT,所以也参考了很多前辈的代码自己重新敲了一遍代码. 游戏介绍: ...

  4. 2022年整理最详细的java面试题、掌握这一套八股文、面试基础不成问题[吐血整理、纯手撸]

    这里是参考B站上的大佬做的面试题笔记.大家也可以去看视频讲解!!! 文章目录 1.面向对象 2.JDK.JRE.JVM区别和联系 3.==和equals 4.final 5.String .Strin ...

  5. C语言------程设设计入门

    仅供借鉴.仅供借鉴.仅供借鉴(整理了一下大一C语言每个章节的练习题.没得题目.只有程序了) 文章目录 1:程序设计入门 2 .实训目的及要求 3.代码实验(包含运行结果) 4 .实验总结 1:程序设计 ...

  6. 一天十道Java面试题----第四天(线程池复用的原理------>spring事务的实现方式原理以及隔离级别)

    这里是参考B站上的大佬做的面试题笔记.大家也可以去看视频讲解!!! 文章目录 31.线程池复用的原理 32.spring是什么? 33.对Aop的理解 34.对IOC的理解 35.BeanFactor ...

  7. Java并发编程 | Synchronized原理与使用

    Java提供了多种机制实现多线程之间有需要同步执行的场景需求.其中最基本的是Synchronized ,实现上使用对象监视器( Monitor ). Java中的每个对象都是与线程可以锁定或解锁的对象 ...

  8. .Net Core中获取appsettings.json中的节点数据

    获取ConnectionStrings节点数据 //appsettings.json { "ConnectionStrings": { //DEV "DbConn&quo ...

  9. 二进制安装JDK和Tomcat

    Oracle JDK的二进制文件安装 https://www.oracle.com/java/technologies/java-se-glance.html #官网下载地址 [root@rocky8 ...

  10. 微信支付v3接口的 官方 Java SDK

    啰嗦几句:微信支付v3版接口麻烦吗?在对接微信支付v3接口时,本来是一件很简单的事情,其实微信支付v3接口并不是很复杂,但是微信团队的管理很混乱,给我们开发者带来了巨大的麻烦. 微信支付v3版接口对接 ...