SpringBoot使用RestTemplate发送http请求(实操版)
warning:
这篇文章距离上次修改已过428天,其中的内容可能已经有所变动。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
@Service
public class RestTemplateService {
@Autowired
private RestTemplate restTemplate;
public String sendGetRequest(String url) {
return this.restTemplate.getForObject(url, String.class);
}
public String sendPostRequest(String url, Object request) {
return this.restTemplate.postForObject(url, request, String.class);
}
}这段代码定义了一个服务类RestTemplateService,它使用RestTemplate发送GET和POST请求。sendGetRequest方法接收URL并返回请求结果,而sendPostRequest方法除了URL还接收一个请求对象,并返回请求结果。这里的String.class表示我们期望返回的响应类型是字符串。在实际使用时,你可以根据需要更改返回类型。
评论已关闭