ServiceNowのREST APIをJavaで実行
ServiceNowのREST API ExplorerではJavaでの方法がなく、キックに結構困ったのでここに残しておきます。
誰かの参考になれば幸いです。
import java.io.*;
import java.net.ProtocolException;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.Base64;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class ServiceNowApi {
// ユーザーIDやパスワードは適切なものに書き換えてください
private static String user = "admin";
private static String password = "xxxxxx";
public static void main(String[] args) throws IOException {
// テスト用のIncident tableのGETをするAPI実行
getMethod();
}
private static void getMethod() throws IOException {
try {
// URLは適切なものに書き換えてください
String url = "https://xxxxxx.service-now.com/api/now/table/incident?sysparm_limit=1";
HttpsURLConnection con = getAllTrustingHttpsUrlConnection(url);
con.setRequestMethod("GET");
con.setRequestProperty("Accept", "application/json");
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("user", user
+ ":"
+ password);
String authString = getAuthorizationString();
con.setRequestProperty("Authorization", "Basic "
+ authString);
con.connect();
// サーバーからのレスポンスを標準出力へ出す
String res = "", line = "";
int status = con.getResponseCode();
switch (status) {
case 200:
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
while ((line = reader.readLine()) != null) {
res = res
+ line;
}
reader.close();
System.err.println(res);
return;
case 404:
System.err.println("test 404");
case 500:
InputStream stream = con.getErrorStream();
BufferedReader bufferReader = new BufferedReader(new InputStreamReader(stream));
while ((line = bufferReader.readLine()) != null) {
res = res
+ line;
}
bufferReader.close();
System.err.println("test 500");
default:
System.err.println("test default");
}
con.disconnect();
} catch (ProtocolException e) {
e.printStackTrace();
}
}
/*
* * Create a trust manager which accepts all certificates and * use this
* trust
* manager to initialize the SSL Context. * Create a HttpsURLConnection for
* this
* SSL Context and skip * server hostname verification during SSL handshake.
* * *
* Note: Trusting all certificates or skipping hostname verification * is
* not
* required for API Services to work. These are done here to * keep this
* sample
* REST Client code as simple as possible.
*/ private static HttpsURLConnection getAllTrustingHttpsUrlConnection(String server_url) {
HttpsURLConnection conn = null;
try {
/*
* Creating a trust manager that does not validate certificate
* chains
*/ TrustManager[] trustAllCertificatesManager = new TrustManager[] { new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
} }; /*
* Initialize the SSLContext with the all-trusting trust
* manager
*/
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustAllCertificatesManager, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
URL url = new URL(server_url);
conn = (HttpsURLConnection) url.openConnection();
/*
* Do not perform an actual hostname verification during SSL
* Handshake. Let all hostname pass through as verified.
*/ conn.setHostnameVerifier(new HostnameVerifier() {
public boolean verify(String host, SSLSession session) {
return true;
}
});
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
/*
* * This forms the Base64 encoded string using the username and password *
* provided by the user. This is required for HTTP Basic Authentication.
*/ private static String getAuthorizationString() {
Charset charset = StandardCharsets.UTF_8;
String userPassword = user
+ ":"
+ password;
//byte[] authEncodedBytes = Base64.encodeBase64(userPassword.getBytes());
byte[] authEncodedBytes = Base64.getEncoder().encode(userPassword.getBytes(charset));
String authString = new String(authEncodedBytes);
return authString;
}
public static String convertToString(InputStream stream) throws IOException {
StringBuffer sb = new StringBuffer();
String line = "";
BufferedReader br = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
while ((line = br.readLine()) != null) {
sb.append(line);
}
try {
stream.close();
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}
}