java调用restful接口的有哪些方法
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 entity = new HttpEntity<>("", headers);
ResponseEntity response = restTemplate.exchange("http://example.com/api/resource", HttpMethod.GET, entity, String.class);
if (response.getStatusCode() == HttpStatus.OK) {
String responseBody = response.getBody();
// 处理响应数据
}
这些方法都可以根据需要设置要求方法、要求头、要求参数等,发送要求并获得响应数据。具体使用哪一种方法取决于个人的偏好和项目的需求。
TOP