Spring RestTemplate 之get请求

一,简介:Spring RestTemplate 是 Spring 提供的用于访问 Rest 服务的客户端,RestTemplate 提供了多种便捷访问远程Http服务的方法,能够大大提高客户端的编写效率

二、RestTemplate中几种常见请求方法的使用

●get请求:在RestTemplate中,发送一个GET请求,我们可以通过如下两种方式

第一种:getForEntity

getForEntity方法的返回值是一个ResponseEntity<T>,ResponseEntity<T>是Spring对HTTP请求响应的封装,包括了几个重要的元素,如响应码、contentType、contentLength、响应消息体等。例子:

@Controller

@RequestMapping("/restTest")

public class RestTempLateTest {

private RestTemplate restTemplate = new RestTemplate();

@RequestMapping("/hello")

@ResponseBody

public String getHello() {

// ResponseEntity<IntMonitor> res = restTemplate.getForEntity(url,

// IntMonitor)

ResponseEntity<String> res = restTemplate.getForEntity(

"http://10.145.198.143:8081/ords/data_service/monitor/IntMonitor",

String.class);

String body = res.getBody();

return body;

}

}

有时候我在调用服务提供者提供的接口时,可能需要传递参数,有两种不同的方式,如下

@RequestMapping("/hello1/{flag}")

@ResponseBody

public String getHello1(@PathVariable String flag){

ResponseEntity<String> res = restTemplate.getForEntity(

"http://10.145.198.143:8081/ords/data_service/monitor/IntMonitor/{1}",

String.class,

"1");

String body = res.getBody();

return body;

}

@RequestMapping("/hello2/{flag}")

@ResponseBody

public String getHello2(@PathVariable String flag){

Map<String, Object> map = new HashMap<String, Object>();

map.put("flag", flag);

ResponseEntity<String> res = restTemplate.getForEntity(

"http://10.145.198.143:8081/ords/data_service/monitor/IntMonitor/{flag}",

String.class,

map);

String body = res.getBody();

return body;

}

@RequestMapping("/hello3/{flag}")

@ResponseBody

public String getHello3(@PathVariable String flag) {

UriComponents uriComponents = UriComponentsBuilder

.fromUriString(

"http://10.145.198.143:8081/ords/data_service/monitor/IntMonitor/{flag}")

.build().expand(flag);

URI uri = uriComponents.toUri();

ResponseEntity<String>  res = restTemplate.getForEntity(uri, String.class);

String body = res.getBody();

return body;

}

  • 可以用一个数字做占位符,最后是一个可变长度的参数,来一一替换前面的占位符
  • 也可以前面使用name={name}这种形式,最后一个参数是一个map,map的key即为前边占位符的名字,map的value为参数值
  • 调用地址也可以是一个url,而不是一个字符串,这样可以直接调用url.

第二种:getForObject

getForObject函数实际上是对getForEntity函数的进一步封装,如果你只关注返回的消息体的内容,对其他信息都不关注,此时可以使用getForObject,

举一个简单的例子,如下:

@RequestMapping("/hello4/{flag}")

@ResponseBody

public String getHello4(@PathVariable String flag) {

UriComponents uriComponents = UriComponentsBuilder

.fromUriString(

"http://10.145.198.143:8081/ords/data_service/monitor/IntMonitor/{flag}")

.build().expand(flag);

URI uri = uriComponents.toUri();

String  res = restTemplate.getForObject(uri, String.class);

return res;

}

原文地址:https://www.cnblogs.com/jnba/p/10522554.html

时间: 2024-08-13 18:27:46

Spring RestTemplate 之get请求的相关文章

Spring RestTemplate 小结

关于RestTemplate 首先,你可以把它理解为一个发起请求并接收响应的工具类(功能类似浏览器). 其次,它其实是一个壳,具体还是通过调用别的接口来实现(如jdk自带的连接,或者HttpClient之类的,需要设置). 官方介绍 Spring's central class for synchronous client-side HTTP access. It simplifies communication with HTTP servers, and enforces RESTful p

spring restTemplate 用法

发出get请求,方式一 String url = serverUrl+"/path/path?id={id}"; int i = restTemplate.getForObject(url,int.class,id); 发出get请求,方式二 URI url= UriComponentsBuilder.fromUriString(serverUrl) .path("/path/") .queryParam("key", key) .queryPa

spring mvc对异步请求的处理

在spring mvc3.2及以上版本增加了对请求的异步处理,是在servlet3的基础上进行封装的. 1.修改web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001

Spring源码阅读:Spring MVC 如何处理HTTP请求

Spring MVC 对HTTP请求的处理流程 通过之前的源码阅读,知道了ApplicationContext初始的过程,也知道了Spring MVC环境的初始化过程,今天就来了解一下SpringMVC是如何处理HTTP请求的. HTTP请求根据请求方式可以分为GET.POST.PUT.DELETE.OPTIONS.TRACE,最常用的还是GET和POST. Spring对于这几种HTTP请求的处理都是使用了processRequest(req,rep); @Override protected

使用RestTemplate发送post请求

最近使用RestTemplate发送post请求,遇到了很多问题,如转换httpMessage失败.中文乱码等,调了好久才找到下面较为简便的方法: RestTemplate restTemplate = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8"); head

Spring MVC(二) HTTP请求数据的绑定

HTTP请求数据的绑定 通过注解绑定 @RequestParam-->绑定请求参.@RequestHeader-->绑定请求头参数.@CookieValue-->绑定Cookie的值.@PathVariable-->绑定URL中的 示例: @RequestMapping(value="/handle2")public String handle2(@CookieValue("JSESSIONID") String sessionId,@Req

Spring RestTemplate: 比httpClient更优雅的Restful URL访问

{ "Author": "tomcat and jerry", "url":"http://www.cnblogs.com/tomcatandjerry/p/5899722.html" } Spring RestTemplate, 使用java访问URL更加优雅,更加方便. 核心代码: String url = "http://localhost:8080/json"; JSONObject json =

Spring MVC 处理HTTP请求的整体流程

DispatcherServlet是一个前端控制器,是整个Spring MVC框架的核心组件.它在接收HTTP请求之后,根据请求调用Spring MVC中的各个组件. 常用接口及其含义: 1. Controller:被@Controller修饰的类是控制器类. 2. HandlerMapping:将用户请求映射到控制器. 3. HandlerInterceptor:拦截指定格式的URL请求. 4. ModelAndView:控制器处理完请求后,将视图的逻辑名称和模型数据封装成ModelAndVi

Spring RestTemplate中文乱码解决方案

由于RestTemplate的默认构造方法初始化的StringHttpMessageConverter的默认字符集是ISO-8859-1,所以导致RestTemplate请求的响应内容会出现中文乱码.在这里我就要无力的吐槽一下了,Spring.StringHttpMessageConverter的默认字符集为啥是ISO-8859-1,难道不是UTF-8更通用一些吗?这个问题等大神给我答案吧. 其实本来网上已经有了两种解决方案,但是我并不喜欢那样的解决方案.具体怎么做,各位看官看是仔细查看吧.ht