springboot发送post请求代码示例
时间: 2023-10-29 14:27:33 浏览: 51
以下是一个使用Spring Boot发送POST请求的代码示例:
@RestController
public class ExampleController {
@Autowired
private RestTemplate restTemplate;
@PostMapping("/example")
public String sendPostRequest(@RequestBody ExampleRequest request) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<ExampleRequest> entity = new HttpEntity<>(request, headers);
ResponseEntity<String> response = restTemplate.exchange(
"http://example.com/api/endpoint",
HttpMethod.POST,
entity,
String.class
);
return response.getBody();
}
}
在这个示例中,我们使用了Spring Boot自带的RestTemplate来发送POST请求。我们通过注入RestTemplate来使用它发送请求。我们创建了一个HttpHeaders对象来设置请求头,然后创建了一个HttpEntity对象,将请求体和请求头放入其中。最后,我们使用RestTemplate的exchange方法来发送请求,并将响应转换为字符串返回。