今回はなるべく自力でZabbixサーバーとやり取りするためのプログラムを作成.
用意するものを少なくするために, httpclientのコーディングは標準ライブラリで何とかする.
用意するもの
ここのDownloadのthe latest JARからjarファイルをダウンロード
HttpClient
ここを参考にした.
ZabbixサーバーにJsonRPCの規則に従ってJSONオブジェクトを投げると, jsonrpc, result, idで構成されたJSONオブジェクトが返ってくる.
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()); //ここでJSONデータを投げる
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; //ここでJSONデータを受け取る
}
}
}
} finally {
if (connection != null) {
connection.disconnect();
}
}
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
}
JSONオブジェクトの作成
クライアントは, jsonrpc, method, params, id, authで構成されるJSONオブジェクトをサーバーに投げる.今回は, バージョンの取得とログインをする.
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);//バージョンの取得の際は必要ない
result = api.Post(json);
System.out.println(result);
param.put("user", "name");//ユーザー名
param.put("password", "pass");//パスワード
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"));
}
}
実行結果
バージョンの取得は生のJSONデータが返ってくるようにした.authはresultから抽出した.
{"jsonrpc":"2.0","result":"4.0.3","id":1}
012225192b38d347ddf6098d291f30df
次はきれいにまとめます.