SpringBoot使用RestTemplate 来调用接口

本文介绍了Spring框架中RestTemplate的配置方法及多种传输和接收参数的方式,包括postForObject、getForObject等方法的具体应用。

1.新建一个配置类,配置RestTemplate的Bean

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

/**
 * RestTemplate配置模板
 *
 * @author like
 */
@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
        return new RestTemplate(factory);
    }

    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setReadTimeout(5000);//单位为ms
        factory.setConnectTimeout(5000);//单位为ms
        return factory;
    }

}

注意点:如果在编译器中提示factory不能自动注入,那应该时跟其他类有冲突,有多个 ClientHttpRequestFactory 

把这个factory的名字改一下,改成其他的就好了,比如这里就直接改成 simpleClientHttpRequestFactory

 

2.多种传输和接收参数的方式

2.1postForObject方法

postForObject指post请求,并返回一个Object对象。

  • 第1个参数:请求的url地址
  • 第2个参数:其实是HttpEntity,这个类主要有三种构造方法,如下
    • new HttpEntity(请求体)
    • new HttpEntity(请求头)
    • new HttpEntity(请求体,请求头)
  • 第3个参数:返回的结果类型,这里String.class表示返回结果是一个字符串。
  • 第4个参数:参数值,这里有Map和 可变参数两种形式(通常用不到,数据通常放在Json里就全部传输过去了

2.1.1使用Json来传递和接收数据

首先引入fastJson的pom配置

<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.2.49</version>
		</dependency>

在实现类中注入RestTemplate

接下来new一个 ExpressionDomain 对象,将这个对象转化成JSONObject。使用Json来传递数据

public void postByDefault()
{
    ExpressionDomain expressionDomain=new ExpressionDomain("hello","hasaki","win");
    JSONObject jsonObj = (JSONObject) JSONObject.toJSON(expressionDomain);
    
    //设置请求头
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
    headers.add("Accept", MediaType.APPLICATION_JSON.toString());

    //请求体
    HttpEntity<String> formEntity = new HttpEntity<String>(jsonObj.toString(), headers);
    
    //发起请求
    String jsonResult = restTemplate.postForObject("http://localhost:8081/findDataByReflection" , formEntity, String.class);
    
    //将Json字符串解析成对象
    Response resp = JSON.parseObject(jsonResult, new TypeReference<Response>() {});
}

接收端

@RequestBody注解一个参数,用于自动解析Json为对象。返回的Response也是一个对象,添加@ResponseBody注解,将返回Json字符串。解析的时候将Json字符串解析成对象即可

postForEntity

和getForEntity原理是一样的,下面会讲到。

 

2.2getForObject方法

getForObject指get请求,并返回一个Object对象。这里有3种方法。

  • 第1个参数:请求的url地址
  • 第2个参数:返回的结果类型,这里String.class表示返回结果是一个字符串。
  • 第3个参数:参数值,这里有Map和 可变参数两种形式

2.2.1 通过Map传参数的方式

  • 可以使用map来封装请求参数,并作为getForObject的第三个参数,同时修改url如下,map中的"1"会替换url中的{1},"2"会替换url中的{2}
Map map = new HashMap();
map.put("1", "hello");
map.put("2", "world");
String result = restTemplate.getForObject("http://localhost:8081/getIds?param1={1}&param2={2}", String.class,map);

接口端:

@RequestMapping(value = "/getIds", method = RequestMethod.GET)
public @ResponseBody String getIds(String param1, String param2) {
    return param1 + param2;
}

2.2.2 通过可变参数的方式

  • 也可以直接将要传递的值放到getForObject方法的参数结尾,数量不限,它会按顺序替换{1}和{2}。接口端代码还是和2.2.1的一样
String result = restTemplate.getForObject("http://localhost:8081/getIds?param1={1}&param2={2}", String.class, "hello", "world");

2.3getForEntity方法

getForEntity和getForObject的用法是一样的,只是其返回结果是一个ResponseEntity,其中包含了更多的响应信息,比如:

		ResponseEntity response = restTemplate.getForEntity("http://localhost:8081/getIds",String.class);
		response.getHeaders();		//响应头
		response.getStatusCode();	//响应码
		response.getBody();			//响应体,即前面的result

 

 

 

 

 

 

 

 

 

 

 

Spring Boot使用`RestTemplate`调用外部接口是一种常见且高效的实践方式。通过`RestTemplate`,可以轻松地发送HTTP请求并处理响应,支持GET、POST、PUT、DELETE等常见HTTP方法。以下是具体的实现步骤和示例代码。 ### 配置RestTemplate Bean 首先,需要将`RestTemplate`配置为Spring容器中的Bean,以便在整个应用中方便地使用。可以通过配置类来定义该Bean: ```java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.client.RestTemplate; @Configuration public class AppConfig { @Bean public RestTemplate restTemplate() { return new RestTemplate(); } } ``` ### 发起GET请求 在实际开发中,GET请求通常用于获取外部服务的数据。以下是一个使用`RestTemplate`发起GET请求的示例: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; @Service public class ExternalService { @Autowired private RestTemplate restTemplate; public String callExternalApi() { String url = "https://api.example.com/data"; return restTemplate.getForObject(url, String.class); } } ``` 上述代码中,`getForObject`方法用于发送GET请求,并将响应体直接转换为指定的类型(如`String`)。 ### 发起POST请求 POST请求通常用于向外部服务提交数据。以下是一个使用`RestTemplate`发起POST请求的示例: ```java import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; @Service public class ExternalService { @Autowired private RestTemplate restTemplate; public String sendPostRequest() { String url = "https://api.example.com/submit"; // 设置请求头 HttpHeaders headers = new HttpHeaders(); headers.set("Content-Type", "application/json"); // 请求体 String requestBody = "{\"key1\":\"value1\", \"key2\":\"value2\"}"; // 构建请求实体 HttpEntity<String> requestEntity = new HttpEntity<>(requestBody, headers); // 发送POST请求 ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class); return responseEntity.getBody(); } } ``` 在该示例中,`exchange`方法用于发送POST请求,并允许自定义请求头和请求体。`HttpEntity`用于封装请求头和请求体,`ResponseEntity`则用于接收完整的响应信息,包括状态码、响应头和响应体。 ### 处理响应 在调用外部接口时,除了获取响应体外,还可以通过`ResponseEntity`获取更多响应信息,例如状态码和响应头: ```java public void handleResponse() { String url = "https://api.example.com/data"; ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class); int statusCode = responseEntity.getStatusCodeValue(); // 获取状态码 String responseBody = responseEntity.getBody(); // 获取响应体 // 处理响应 } ``` ### 高级用法:自定义拦截器 `RestTemplate`还支持自定义拦截器,用于在请求发送前后执行特定逻辑(如日志记录、身份验证等)。以下是一个简单的拦截器示例: ```java import org.springframework.http.HttpRequest; import org.springframework.http.client.ClientHttpRequestExecution; import org.springframework.http.client.ClientHttpRequestInterceptor; import org.springframework.http.client.ClientHttpResponse; import java.io.IOException; public class RequestInterceptor implements ClientHttpRequestInterceptor { @Override public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { // 在请求发送前执行 System.out.println("Intercepting request: " + request.getURI()); // 执行请求 ClientHttpResponse response = execution.execute(request, body); // 在请求发送后执行 System.out.println("Received response with status code: " + response.getStatusCode()); return response; } } ``` 配置拦截器: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.web.client.RestTemplate; @Configuration public class AppConfig { @Autowired private RestTemplate restTemplate; public AppConfig(RestTemplate restTemplate) { this.restTemplate = restTemplate; // 添加拦截器 restTemplate.getInterceptors().add(new RequestInterceptor()); } } ``` ### 总结 通过上述步骤,可以在Spring Boot项目中高效地使用`RestTemplate`调用外部接口。无论是简单的GET请求,还是复杂的POST请求,`RestTemplate`都提供了灵活且强大的支持。此外,通过自定义拦截器,可以进一步增强请求的可观察性和可扩展性。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值