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();
// 處理響應數據
}
這些方法都可以根據需要設置請求方法、請求頭、請求參數等,發送請求并獲取響應數據。具體使用哪種方法取決于個人的偏好和項目的需求。