用Java编写的Zabbix API
这次为了尽量自己与Zabbix服务器进行交互,我要编写一个程序。
为了减少所需准备的工具,我会用标准库来处理httpclient的编码。
有意图的目的
请从这里的“Download the latest JAR”中下载jar文件。
Http客户端
参考这里。
向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数据。身份验证信息从结果中提取。
{"jsonrpc":"2.0","result":"4.0.3","id":1}
012225192b38d347ddf6098d291f30df
下一次我会整理得更干净。