使用restTEmplate实现
时间: 2024-05-10 19:20:22 浏览: 65
RestTemplate实现服务间调用demo案例
RESTful API调用的示例代码如下:
```
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
public class RestTemplateExample {
private static final String API_URL = "https://jsonplaceholder.typicode.com/posts";
public static void main(String[] args) {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.set("Accept", "application/json");
HttpEntity<String> entity = new HttpEntity<>("parameters", headers);
ResponseEntity<String> response = restTemplate.exchange(API_URL, HttpMethod.GET, entity, String.class);
System.out.println(response.getBody());
}
}
```
此代码使用RestTemplate调用了一个GET方法,将请求头设置为“Accept: application/json”,并将响应作为字符串返回。您可以将此代码修改为调用其他HTTP方法,例如POST、PUT、DELETE等。
阅读全文