Springboot HTTP Get/Post 请求讲解,Springboot几行代码完成Http请求

JSON 2019-12-16 22:15:28 71706

以前我们创建一个Http请求,很复杂,要写很多代码,而且请求还有各种兼容问题。而用 RestTemplate 的话优雅的几行代码就可以解决,并且是可以直接返回对象。

RestTemplate 是  Spring  用于同步请求client端的核心类,简化了与  HTTP   的通信,并满足RestFul原则,RestTemplate默认依赖  JDK  的HTTP连接工具。当然你也可以 通过setRequestFactory属性切换到不同的HTTP 数据源,比如Apache HttpComponentsNettyOkHttp,都是支持的。

HTTP Get 请求

我们先做一个普通的Http请求,直接上源码。

try {
    HttpClient client = new HttpClient();
    //创建一个Get请求
    GetMethod method = new GetMethod("http://t.weather.sojson.com/api/weather/city/"+101010100);
    client.executeMethod(method);
    //获取String类型的返回值
    String res = method.getResponseBodyAsString();
    //使用gson转换为对象
    WeatherDto dto = new Gson().fromJson(res,WeatherDto.class);
} catch (IOException e) {
    e.printStackTrace();
}

这是一个最简单的Http请求,把返回值使用   Gson   来转换成对象。

使用RestTemplate HTTP Get 请求

RestTemplate restTemplate = new RestTemplate();
WeatherDto dto = restTemplate.getForObject("http://t.weather.sojson.com/api/weather/city/"+101010100
, WeatherDto.class);

2行代码就完成了,并且将结果转换为对象。

1.RestTemplate URL拼接参数请求

RestTemplate restTemplate = new RestTemplate();
WeatherDto dto = restTemplate.getForObject("http://t.weather.sojson.com/api/weather/city/{1}" , WeatherDto.class,101010100
);

上面其实是一个简单的带参数请求,用“{1}”、“{2}”、“{3}”... 方式传参,如果是地址拼接的方式,可以N个。

上一篇博客采用这个方式,模拟的Http请求,请求天气接口数据:https://www.sojson.com/blog/349.html 。

2.RestTemplate 多个参数请求

因为是Get请求,其实就是问号的方式带参数请求

Map<String,String> map = new HashMap();
map.put("id",101010100);
RestTemplate restTemplate = new RestTemplate();
Details detail = restTemplate.getForObject("http://example.sojson.com/detail.html" , Details.class,map);

3.RestTemplate getForEntity 请求

其实上面的1和2算是简单的请求,就是直接返回了Object 实例对象。而我们要获取详细的详细,如返回statusHeader信息等。那就得用 getForEntity 。

看看源码里的参数描述,其实是和 getForObject 一致,我这里网络不行没下载下来源码包,凑合看看。

<T> ResponseEntity<T> getForEntity(String var1, Class<T> var2, Object... var3) throws RestClientException;

<T> ResponseEntity<T> getForEntity(String var1, Class<T> var2, Map<String, ?> var3) throws RestClientException;

<T> ResponseEntity<T> getForEntity(URI var1, Class<T> var2) throws RestClientException; 

实例讲解:

RestTemplate restTemplate = new RestTemplate();
String url = "http://example.sojson.com/detail.html";
//添加请求头
HttpHeaders headers = new HttpHeaders();
//form表单提交 application/x-www-form-urlencoded
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
//组装参数
MultiValueMap<String, String> map= new LinkedMultiValueMap<>();

map.add("id", "101010100");

HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
ResponseEntity<WeatherDto> response = restTemplate.postForEntity( url, request , WeatherDto.class );
//返回对象
WeatherDto dto = response.getBody();
//HTTP状态
int status = response.getStatusCodeValue();

//Spring 封装的
HttpStatus statusCode = response.getStatusCode();

//封装的对应状态请求,返回来都是 Boolean 类型
statusCode.is2xxSuccessful();//2开头的成功状态
statusCode.is3xxRedirection();//3开头重定向
statusCode.is4xxClientError();//4开头客户端错误
statusCode.is5xxServerError();//5开头服务端异常

具体可以自行测试下。

我们看源码知道还有 Post请求 方法。

restTemplate.postForEntity( ... )
restTemplate.postForObject(... )

方法传参是和上面讲解的 Get请求 的使用方式一模一样。

有兴趣的可以测试下我们的在线 HTTP模拟请求 工具 ,就是采用 restTemplate 实现的。



版权所属:SO JSON在线解析

原文地址:https://www.sojson.com/blog/350.html

转载时必须以链接形式注明原始出处及本声明。

本文主题:

如果本文对你有帮助,那么请你赞助我,让我更有激情的写下去,帮助更多的人。

关于作者
一个低调而闷骚的男人。
相关文章
Springboot HTTP请求Springboot HTTP 请求 Demo。Get/Post
在线HTTP接口测试 - HTTP GET/POST模拟请求测试工具【更新说明】
Http Get 请求,Java 请求工具类封装
Java 实现在线HTTP接口测试 - HTTP GET/POST模拟请求测试工具
Springboot 集成 Ehcache 代码讲解
Java 之 HTTP请求乱码解决,GZIP 返回值乱码解决
Java模拟WSS websocket ssl请求,Java WSS模拟请求代码示例
Springboot 集成Aliyun MQ消息队列,Aliyun 消息队列配置及代码实现
Springboot + Freemarker 集成配置
QUIC / HTTP3 协议详细分析讲解
最新文章
Java获取浏览器请求头(User-Agent),分析浏览器信息,系统信息的几种办法。 137027
最热文章
Java获取浏览器请求头(User-Agent),分析浏览器信息,系统信息的几种办法。 137027
支付扫码

所有赞助/开支都讲公开明细,用于网站维护:赞助名单查看

查看我的收藏

正在加载... ...