@Test
public void testZabbixAPI() throws Exception {
String zabbixUser = "zabbixuser";
String zabbixPass = "****";
String zabbixEndpoint = "http://zabbixserver/zabbix/api_jsonrpc.php";
//認証
JSONObject json = new JSONObject();
json.put("user", zabbixUser);
json.put("password", zabbixPass);
json.put("userData", "false");
String token = null;
ResponseEntity<String> response = Request("user.login", json, zabbixEndpoint, token);
JsonNode root = new ObjectMapper().readTree(response.getBody());
token = root.get("result").get("sessionid").asText();
//ホスト情報取得
JSONObject target = new JSONObject();
String[] chkTarget = {"server01","server02"};
JSONArray targetArray = new JSONArray(chkTarget);
JSONObject param = new JSONObject();
param.put("output", new JSONArray(Arrays.asList("hostid","host","name")));
target.put("host", targetArray);
param.put("filter", target);
response = Request("host.get", param, zabbixEndpoint, token);
ObjectMapper mapper = new ObjectMapper();
ArrayNode arrayHost = (ArrayNode) mapper.readTree(response.getBody()).path("result");
System.out.println("hosts: " + arrayHost);
}
private ResponseEntity<String> Request(String method, JSONObject param, String endPoint, String token) throws Exception {
JSONObject json = new JSONObject();
json.put("jsonrpc", "2.0");
json.put("method", method);
json.put("params", param);
json.put("id", 1);
if(token != null){
json.put("auth", token);
}
HttpMethod httpMethod = HttpMethod.POST;
HttpEntity <String> entity ;
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "application/json-rpc");
headers.add("Accept-Language", "ja");
if(param == null){
entity = new HttpEntity <String>(headers);
}
else{
entity = new HttpEntity <String>(json.toString(), headers);
}
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters()
.add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));
ResponseEntity<String> response = restTemplate.exchange(endPoint, httpMethod, entity, String.class);
return response;
}