This time, I created a program to interact with Zabbix server on my own. In order to reduce the amount of preparation, the coding of httpclient is managed by the standard library.
Download the jar file from the latest JAR in Download here
I referred to here. If you throw a JSON object to Zabbix server according to JsonRPC rules, a JSON object composed of jsonrpc, result and id will be returned.
public class Api {
public String Post(JSONObject json) {
try {
URL url = new URL("http://127.0.0.1/zabbix/api_jsonrpc.php");
HttpURLConnection connection = null;
try {
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(),
StandardCharsets.UTF_8));
writer.write(json.toString()); //Throw JSON data here
writer.flush();
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
try (InputStreamReader isr = new InputStreamReader(connection.getInputStream(),
StandardCharsets.UTF_8);
BufferedReader reader = new BufferedReader(isr)) {
String line;
while ((line = reader.readLine()) != null) {
return line; //Receive JSON data here
}
}
}
} finally {
if (connection != null) {
connection.disconnect();
}
}
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
}
The client throws a JSON object consisting of jsonrpc, method, params, id, auth to the server. This time, get the version and log in.
public class Main {
public static void main(String[] args) {
String result;
Api api = new Api();
JSONObject json = new JSONObject();
JSONObject param = new JSONObject();
json.put("jsonrpc", "2.0");
json.put("method", "apiinfo.version");
json.put("params", param);
json.put("id", 1);
json.put("auth", null);//Not required when getting the version
result = api.Post(json);
System.out.println(result);
param.put("user", "name");//username
param.put("password", "pass");//password
json.put("jsonrpc", "2.0");
json.put("method", "user.login");
json.put("params", param);
json.put("id", 1);
json.put("auth", null);
result = api.Post(json);
System.out.println(JSON.parseObject(result).get("result"));
}
}
The version was fetched so that the raw JSON data was returned. Auth was extracted from the result.
{"jsonrpc":"2.0","result":"4.0.3","id":1}
012225192b38d347ddf6098d291f30df
Next is a neat summary.
Recommended Posts