Java调用RESTful接口的方法有多种,以下是其中几种常用的方法:
URL url = new URL("http://example.com/api/resource");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "application/json");
// 设置其他请求头
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream inputStream = connection.getInputStream();
// 处理响应数据
}
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("http://example.com/api/resource");
httpGet.setHeader("Content-Type", "application/json");
// 设置其他请求头
CloseableHttpResponse response = httpClient.execute(httpGet);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
// 处理响应数据
EntityUtils.consume(entity);
}
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<>("", headers);
ResponseEntity<String> response = restTemplate.exchange("http://example.com/api/resource", HttpMethod.GET, entity, String.class);
if (response.getStatusCode() == HttpStatus.OK) {
String responseBody = response.getBody();
// 处理响应数据
}
这些方法都可以根据需要设置请求方法、请求头、请求参数等,发送请求并获取响应数据。具体使用哪种方法取决于个人的偏好和项目的需求。