方法一、使用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. POJ3041 小行星 (二分图匹配模板)

    学了这么久连模板都没有写过,我来补个坑...... 将行看成集合X,列看成Y,障碍看成是X到Y的一条边. 消除次数最少,等价于最小点覆盖问题,最小点覆盖=最大匹配数,跑一遍匈牙利就行了 #includ ...

  2. HDU2196 Computer (树形DP-换根)

    dp[u][0]表示u向下走的最大距离: dp[u][1]表示u向下走的次大距离: dp[u][2]表示u向上走的最大距离: 最后的答案就是每个点的max(dp[u][0],dp[u][2]); 求解 ...

  3. DVWA File Upload level high 通关

    由于level 是 high 1.代码审计 <?php if( isset( $_POST[ 'Upload' ] ) ) { // Where are we going to be writi ...

  4. 它让你1小时精通RabbitMQ消息队列(新增死信处理)

    支持.NET/.NET Framework/.NET Core RabbitMQ作为一款主流的消息队列工具早已广受欢迎.相比于其它的MQ工具,RabbitMQ支持的语言更多.功能更完善. 本文提供一种 ...

  5. 陆地观测卫星数据服务(CRESDA)订单ftp地址错误—已解决不能下载问题

    陆地观测卫星数据服务订单ftp地址错误 问题:本人在陆地观测卫星数据网站上申请GF1-WFV10幅数据,订单完成后返回的FTP地址出现无法连接服务器现象.(数据订单申请已通过) 一.情况介绍: ​ 我 ...

  6. Python凯撒密码加解密

    #凯撒密码第一个版本 #加密 pxpt=input("请输入明文文本:") for p in pxpt: if 'a'<=p<='z': print(chr(ord(' ...

  7. win10本地python第三方库安装成功,但是pycharm项目无法使用解决方案

    一.背景win10本地python第三方库安装成功,但是pycharm项目无法使用解决方案如本地安装的python中的request库,在pycharm项目中居然无法使用,比较郁闷 pip list ...

  8. SpringCloud怎么迈向云原生?

    很多公司由于历史原因,都会有自研的RPC框架. 尤其是在2015-2017期间,Spring Cloud刚刚面世,Dubbo停止维护多年,很多公司在设计自己的RPC框架时,都会基于Spring Clo ...

  9. 【神经网络】softmax回归

    前言 softmax回归为一种分类模型. 基本原理 由于softmax回归也是一种线性叠加算法,且需要输出离散值. 很自然地想到,可以取值最大的输出为置信输出.更进一步想到,如果有三个人A.B.C分别 ...

  10. perl哈希嵌套和引用的使用

    数组,哈希嵌套 数组,哈希的引用 1.哈希的嵌套和引用 %hash = ( 'group1', {'fruit', 'banana', 'drink', 'orange juice', 'vegeta ...