springboot -RestTemplate 发送请求
看这个学的
https://www.bilibili.com/video/BV1Zf4y1U7p5?from=search&seid=9719059667753019566&spm_id_from=333.337.0.0
也可以参考下这个(几种写法)
https://blog.csdn.net/u012702547/article/details/77917939
请求头的写法参考这个
https://zhuanlan.zhihu.com/p/151984334
配置文件可以参考这个:
https://www.jianshu.com/p/95680c1eb6e0
请求配置文件
package com.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.client.RestTemplate; @Configuration public class Restemconnfig { @Autowired private RestTemplateBuilder builder; @Bean public RestTemplate restTemplate(){ return builder.build(); } } |
上面配置文件也可以这样写
@Configuration
public class Restemconnfig {
@Bean
@LoadBalanced //配置负载均衡实现---Ribbon
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
-----------------------------------------------------------------------------Get请求发送-----------------------------------------------------------------------------
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | import org.springframework.web.client.RestTemplate; @Autowired private RestTemplate restTemplate; @Service @Slf4j public class RequestUrlServer { private final String url= "http://localhost:8280/tool/aaa" ; @Autowired private RestTemplate restTemplate; public User resQuest(){ ResponseEntity responseEntity =restTemplate.getForEntity(url,String. class ); log.info( "响应: " +responseEntity); // 获取响应体 String body = responseEntity.getBody(); log.info(String.valueOf(body)); // 获取响应码 int Code = responseEntity.getStatusCodeValue(); log.info(String.valueOf(Code)); // 获取请求头 HttpHeaders Headers = responseEntity.getHeaders(); log.info(String.valueOf(Headers)); return null ; } |
- getForEntity第二个参数String.class表示我希望返回的body类型是String
拼接url 发送请求
private final String url = "http://localhost:8280/tool/{id}";
1
2
3
4
5
6
|
<code> public Map resQuest() { Map map2= new HashMap(); map2.put( "id" , "aaa" ); // 发送请求 ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String. class ,map2); </code> |
-----------------------------------------------------------------------------Post请求发送-----------------------------------------------------------------------------
1 2 | ---data的话也是这么传的 亲测ok map2= "uuu=123" |
1 2 3 4 5 6 7 8 9 10 11 12 13 | @Service @Slf4j public class RequestUrlServer { private final String url = "http://localhost:8380/tool/aaa" ; @Autowired private RestTemplate restTemplate; public Map resQuest() { //请求参数 Map map2= new HashMap(); map2.put( "name" , "aaa" ); // 发送请求 ResponseEntity responseEntity = restTemplate.postForEntity(url,map2,String. class ); |
------------------------------------------------------------------------返回值处理方法---------------------------------------------------
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | // //第一种取值方法 // JSONObject jsonObject = JSONObject.parseObject(body); // log.info("响应体: " + body); // log.info("响应体: " + jsonObject); // log.info("响应体: " + jsonObject.get("name")); // // //第二种取值方法 // Map<string, string=""> map = JSONObject.<map<string, string="">>parseObject(body, Map.class); // log.info("响应体1: " + map); // //// 第三种映射到类里面 // User user = JSONObject.parseObject(body, User.class); // log.info(user.toString()); 方法分别 返回类型 Map or User 其中User是根据返回的json 来定义 如响应返回 { "name" : "张三" } User类为 import lombok.Data; @Data public class User { private String name; } </map<string,></string,> |
---------------------------------------------------------------------带上headers请求头 请求的 方法------------------------------------------------------------
- 希望复用 HttpHeaders
headers.add
方式添加请求头;而不是前面的set
方式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | public class RequestUrlServer { private final String url = "http://localhost:8380/tool/bbb" ; private final String url2 = "http://localhost:8380/tool/aaa" ; @Autowired private RestTemplate restTemplate; public int resQuest() { HttpHeaders headers = new HttpHeaders(); headers.set( "user-agent" , "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36" ); headers.set( "cookie" , "my_user_id=haha123; UN=1231923;gr_user_id=welcome_yhh;" ); // 请求bady参数 Map map2= new HashMap(); map2.put( "name" , "aaa" ); // 发送post请求带上heard String response = restTemplate.postForObject(url2, new HttpEntity<>(map2, headers), String. class ); log.info( "post with selfDefine header: {}" , response); //发送Get请求带上heard ResponseEntity response2 = restTemplate.exchange(url, HttpMethod.GET, new HttpEntity<>( null , headers),String. class ); log.info( "get with selfDefine header: {}" , response2); |
------------------------------------------------------------统一加上请求头的写法------------------------------------------------------------
参考: https://zhuanlan.zhihu.com/p/151984334
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | public int resQuest() { // 借助拦截器的方式来实现塞统一的请求头 ClientHttpRequestInterceptor interceptor = (httpRequest, bytes, execution) -> { httpRequest.getHeaders().set( "user-agent" , "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36" ); httpRequest.getHeaders().set( "cookie" , "my_user_id=haha123; UN=1231923;gr_user_id=interceptor;" ); return execution.execute(httpRequest, bytes); }; // 统一加入请求头 restTemplate.getInterceptors().add(interceptor); // 请求bady参数 Map map2= new HashMap(); map2.put( "name" , "aaa" ); // 发送post请求带上heard String response2 = restTemplate.postForObject(url2,map2,String. class ); log.info( "post with selfDefine header: {}" , response2); // get请求 String response = restTemplate.getForObject(url, String. class ); log.info( "get with selfDefine header by Interceptor: {}" , response); |
-------------------------------------------------------------------接口接收请求头的写法-------------------------------------------------------------------
1 2 3 4 5 6 | @PostMapping ( "/aaa" ) public User delete_User3 ( @RequestBody User user, HttpServletRequest HttpServletRequest) { log.info(String.valueOf(user)); log.info(HttpServletRequest.getHeader( "cookie" )); return user; } |
-----------------------------------------------------------------配置文件 参数---------------------------------
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | import org.apache.http.client.HttpClient; import org.apache.http.conn.HttpClientConnectionManager; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.web.client.RestTemplate; @Configuration public class RestTemplateConfig { /** * http连接管理器 * @return */ @Bean public HttpClientConnectionManager poolingHttpClientConnectionManager() { /*// 注册http和https请求 Registry registry = RegistryBuilder.create() .register("http", PlainConnectionSocketFactory.getSocketFactory()) .register("https", SSLConnectionSocketFactory.getSocketFactory()) .build(); PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager(registry);*/ PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager(); // 最大连接数 poolingHttpClientConnectionManager.setMaxTotal( 500 ); // 同路由并发数(每个主机的并发) poolingHttpClientConnectionManager.setDefaultMaxPerRoute( 100 ); return poolingHttpClientConnectionManager; } /** * HttpClient * @param poolingHttpClientConnectionManager * @return */ @Bean public HttpClient httpClient(HttpClientConnectionManager poolingHttpClientConnectionManager) { HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); // 设置http连接管理器 httpClientBuilder.setConnectionManager(poolingHttpClientConnectionManager); /*// 设置重试次数 httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(3, true));*/ // 设置默认请求头 /*List |
headers = new ArrayList<>();
headers.add(new BasicHeader("Connection", "Keep-Alive"));
httpClientBuilder.setDefaultHeaders(headers);*/
return httpClientBuilder.build();
}
/**
* 请求连接池配置
* @param httpClient
* @return
*/
@Bean
public ClientHttpRequestFactory clientHttpRequestFactory(HttpClient httpClient) {
HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory();
// httpClient创建器
clientHttpRequestFactory.setHttpClient(httpClient);
// 连接超时时间/毫秒(连接上服务器(握手成功)的时间,超出抛出connect timeout)
clientHttpRequestFactory.setConnectTimeout( 5 * 1000 );
// 数据读取超时时间(socketTimeout)/毫秒(务器返回数据(response)的时间,超过抛出read timeout)
clientHttpRequestFactory.setReadTimeout( 10 * 1000 );
// 连接池获取请求连接的超时时间,不宜过长,必须设置/毫秒(超时间未拿到可用连接,会抛出org.apache.http.conn.ConnectionPoolTimeoutException: Timeout waiting for connection from pool)
clientHttpRequestFactory.setConnectionRequestTimeout( 10 * 1000 );
return clientHttpRequestFactory;
}
/**
* rest模板
* @return
*/
@Bean
public RestTemplate restTemplate(ClientHttpRequestFactory clientHttpRequestFactory) {
// boot中可使用RestTemplateBuilder.build创建
RestTemplate restTemplate = new RestTemplate();
// 配置请求工厂
restTemplate.setRequestFactory(clientHttpRequestFactory);
return restTemplate;
}
}
接口接收请求的看这儿
https://www.cnblogs.com/kaibindirver/p/15524830.html
后记:
操作响应的json---- com.alibaba.fastjson 用的是这个库
1 2 3 | com.alibaba fastjson 1.2.47 |
1 2 3 4 5 | 发送请求 JSONObject response = restTemplate.postForObject(url2, new HttpEntity<>(data, headers), JSONObject. class ); log.info( "响应: " + response); String s = response.getString( "code" ); System. out .println(s); |
如果是返回String类型 (长得像json的string)
1 2 3 | String response = restTemplate.postForObject(url2, new HttpEntity<>(map2, headers), String. class ); JSONObject object = JSON.parseObject(response); |
获取json 键对应的数组
JSONArray jsonArray = data2.getJSONArray("logs");
获取数组里面对应的 json
for (int i=0;i<jsonArray.size();i++){
获取数组里面对应的 json
HashMap aa= (HashMap) jsonArray.get(i);
获取json里面对应键的值
String tager= (String) aa.get("content");
------------------------------------判断字符类型用上 lucaxdata.getClass().getName()
13、string转json格式,获取里面得到 数组或json格式的值
String targe2="{'aaa':11111,'bbb':[1,2,3,4,5,6]}";
string转json格式
JSONObject object = JSON.parseObject(targe2);;
获取json里面的aaaa的值
String object2 = targe2.getString("aaa");
如果哦aaa的值还是json
JSONObject object2 = targe2.getJSONObject("aaa");
获取json里面的数组
JSONArray object2 = targe2.getJSONArray("bbb");
这个不错,可以参考处理请求响应回来的json
https://www.runoob.com/w3cnote/java-json-instro.html
https://www.cnblogs.com/chushujin/p/11371450.html
后记:
响应是非200请求会抛异常,可以用try去捕获
见 https://www.cnblogs.com/kaibindirver/p/15948384.html
传参数为from表单,用下面方法发送
MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<>();
paramMap.add("secToken", "FuVYdeF1");
paramMap.add("LogStoreName", "production-education");
paramMap.add("ProjectName", "kuebernetes-production");
// 发送请求
JSONObject retul = restTemplate.postForObject(url2, new HttpEntity<>(paramMap, headers), JSONObject.class);
System.out.println(retul);
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
2020-10-12 v-cli 全局格式化
2020-10-12 有空看看 学习下
2019-10-12 Qps 和 tps的解释
2019-10-12 jmeter 随机取一个值的方法
2018-10-12 操作文件
2018-10-12 克隆别人的仓库,提交到自己的远程仓库的方法
2018-10-12 时间戳变成 标准时间展示的方法