Springboot如何调用携带参数第三方接口
时间: 2024-06-08 20:05:35 浏览: 74
springboot 异步调用的实现方法
SpringBoot可以使用RestTemplate来调用第三方接口,并且可以携带参数。以下是一个简单的示例:
```java
@RestController
public class MyController {
@Autowired
private RestTemplate restTemplate;
@GetMapping("/callThirdPartyApi")
public String callThirdPartyApi() {
String url = "http://third-party-api.com/api";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
MultiValueMap<String, String> params= new LinkedMultiValueMap<>();
params.add("param1", "value1");
params.add("param2", "value2");
HttpEntity<MultiValueMap<String, String>> requestEntity= new HttpEntity<>(params, headers);
ResponseEntity<String> response= restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
return response.getBody();
}
}
```
这里使用RestTemplate发送POST请求,并设置请求头和请求参数。注意,使用RestTemplate之前需要在配置类中添加@Bean注解创建RestTemplate实例,并且需要在pom.xml文件中添加依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web-services</artifactId>
</dependency>
```
阅读全文