Zabbix API in Java

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.

What to prepare

Download the jar file from the latest JAR in Download here

HttpClient

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 "";
    }
}

Creating a JSON object

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"));
    }
}

Execution 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

Zabbix API in Java
Hit Zaim's API (OAuth 1.0) in Java
Parsing the COTOHA API in Java
JPA (Java Persistence API) in Eclipse
Partization in Java
Rock-paper-scissors in Java
Java Stream API
Pi in Java
FizzBuzz in Java
I tried using Elasticsearch API in Java
Implement API Gateway Lambda Authorizer in Java Lambda
Studying Java 8 (date API in java.time package)
Try using the Stream API in Java
Call the Windows Notification API in Java
Try using JSON format API in Java
Get history from Zabbix server in Java
[java] sort in list
Read JSON in Java
Interpreter implementation in Java
Make Blackjack in Java
Rock-paper-scissors app in Java
Constraint programming in Java
Put java8 in centos7
NVL-ish guy in Java
Combine arrays in Java
"Hello World" in Java
Pack API response (java)
Callable Interface in Java
ChatWork4j for using the ChatWork API in Java
[Java] API creation using Jerjey (Jax-rs) in eclipse
[Java] Stream API / map
Azure functions in java
Docker-Client Java API Troubleshooting
Simple htmlspecialchars in Java
Try using GCP's Cloud Vision API in Java
Boyer-Moore implementation in Java
Hello World in Java
webApi memorandum in java
Type determination in Java
Ping commands in Java
Various threads in java
Heapsort implementation (in java)
ASCII art in Java
Compare Lists in Java
POST JSON in Java
Express failure in Java
Create JSON in Java
Date manipulation in Java 8
What's new in Java 8
Try using the COTOHA API parsing in Java
Use PreparedStatement in Java
What's new in Java 9,10,11
Parallel execution in Java
Initializing HashMap in Java
I tried Mastodon's Toot and Streaming API in Java
Call Amazon Product Advertising API 5.0 (PA-API v5) in Java
I tried using Google Cloud Vision API in Java
Try using RocksDB in Java
Read binary files in Java 1
Get EXIF information in Java
Save Java PDF in Excel