Skip to main content
Active IQ Unified Manager 9.14
본 한국어 번역은 사용자 편의를 위해 제공되는 기계 번역입니다. 영어 버전과 한국어 버전이 서로 어긋나는 경우에는 언제나 영어 버전이 우선합니다.

Hello API 서버

기여자

Hello API server_는 간단한 REST 클라이언트를 사용하여 Active IQ Unified Manager에서 REST API를 호출하는 방법을 보여 주는 샘플 프로그램입니다. 샘플 프로그램은 API 서버에 대한 기본 세부 정보를 JSON 형식으로 제공합니다(서버는 형식만 지원 application/json).

사용되는 URI는 다음과 같습니다. https://<hostname>/api/datacenter/svm/svms. 이 샘플 코드는 다음과 같은 입력 매개 변수를 사용합니다.

  • API 서버 IP 주소 또는 FQDN

  • 선택 사항: 포트 번호(기본값: 443)

  • 사용자 이름입니다

  • 암호

  • 응답 형식(application/json)

REST API를 호출하려면 Jersey 및 RESTEasy와 같은 다른 스크립트를 사용하여 Active IQ Unified Manager용 Java REST 클라이언트를 작성할 수도 있습니다. 샘플 코드에 대한 다음 고려 사항을 숙지해야 합니다.

  • Active IQ Unified Manager에 대한 HTTPS 연결을 사용하여 지정된 REST URI를 호출합니다

  • Active IQ Unified Manager에서 제공한 인증서를 무시합니다

  • 핸드셰이크 중에 호스트 이름 확인을 건너뜁니다

  • `javax.net.ssl.HttpsURLConnection`URI 연결에 사용합니다

  • 타사 라이브러리 (`org.apache.commons.codec.binary.Base64`사용)를 사용하여 HTTP 기본 인증에 사용되는 Base64 인코딩된 문자열을 구성합니다

샘플 코드를 컴파일하고 실행하려면 Java 컴파일러 1.8 이상을 사용해야 합니다.

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
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;
import org.apache.commons.codec.binary.Base64;

public class HelloApiServer {

	private static String server;
	private static String user;
	private static String password;
	private static String response_format = "json";
	private static String server_url;
	private static String port = null;

	/*
	 * * The main method which takes user inputs and performs the * necessary steps
	 * to invoke the REST URI and show the response
	 */ public static void main(String[] args) {
		if (args.length < 2 || args.length > 3) {
			printUsage();
			System.exit(1);
		}
		setUserArguments(args);
		String serverBaseUrl = "https://" + server;
		if (null != port) {
			serverBaseUrl = serverBaseUrl + ":" + port;
		}
		server_url = serverBaseUrl + "/api/datacenter/svm/svms";
		try {
			HttpsURLConnection connection = getAllTrustingHttpsUrlConnection();
			if (connection == null) {
				System.err.println("FATAL: Failed to create HTTPS connection to URL: " + server_url);
				System.exit(1);
			}
			System.out.println("Invoking API: " + server_url);
			connection.setRequestMethod("GET");
			connection.setRequestProperty("Accept", "application/" + response_format);
			String authString = getAuthorizationString();
			connection.setRequestProperty("Authorization", "Basic " + authString);
			if (connection.getResponseCode() != 200) {
				System.err.println("API Invocation Failed : HTTP error code : " + connection.getResponseCode() + " : "
						+ connection.getResponseMessage());
				System.exit(1);
			}
			BufferedReader br = new BufferedReader(new InputStreamReader((connection.getInputStream())));
			String response;
			System.out.println("Response:");
			while ((response = br.readLine()) != null) {
				System.out.println(response);
			}
			connection.disconnect();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/* Print the usage of this sample code */ private static void printUsage() {
		System.out.println("\nUsage:\n\tHelloApiServer <hostname> <user> <password>\n");
		System.out.println("\nExamples:\n\tHelloApiServer localhost admin mypassword");
		System.out.println("\tHelloApiServer 10.22.12.34:8320 admin password");
		System.out.println("\tHelloApiServer 10.22.12.34 admin password ");
		System.out.println("\tHelloApiServer 10.22.12.34:8212 admin password \n");
		System.out.println("\nNote:\n\t(1) When port number is not provided, 443 is chosen by default.");
	}

	/* * Set the server, port, username and password * based on user inputs. */ private static void setUserArguments(
			String[] args) {
		server = args[0];
		user = args[1];
		password = args[2];
		if (server.contains(":")) {
			String[] parts = server.split(":");
			server = parts[0];
			port = parts[1];
		}
	}

	/*
	 * * 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()    {        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() {
		String userPassword = user + ":" + password;
		byte[] authEncodedBytes = Base64.encodeBase64(userPassword.getBytes());
		String authString = new String(authEncodedBytes);
		return authString;
	}

}