Sample Program to Invoke POST REST API
The following example sends an HTTP POST request to the
/project endpoint
to create a project.
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.cert.X509Certificate; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; public class SampleProgram { private static String userName = "<username>"; private static String password = "<password>"; private static String hostName = "<hostName>"; private static String workspaceId = "<workspaceId>"; private static String version = "3"; private static String tokenGenerationUrl = "https://" + hostName + "/primediscovery/apitoken/request?scope=" + "http://" + hostName + "/api"; private static String projectUrl = "https://" + hostName + "/api/restapi/project"; public static void main(String s[]) throws Exception { String projectJson = callRestURL(); System.out.println("Project:- " + projectJson); } private static JsonNode getAuthTokenDetails() { HttpURLConnection conn = null; try { // Generating the OAuth Token URL tokenUrl = new URL(tokenGenerationUrl); conn = (HttpURLConnection) tokenUrl.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Accept", "application/json"); conn.setRequestProperty("Content-Type", "application/json"); String userCredentials = userName + ":" + password; String base64Credentials = javax.xml.bind.DatatypeConverter.printBase64Binary(userCredentials.getBytes()); String basicAuth = "Basic " + base64Credentials; conn.setRequestProperty("Authorization", basicAuth); if (conn.getResponseCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode() + "Error: " + readStreamData(conn.getErrorStream())); } JsonNode authTokenJson = new ObjectMapper().readValue(conn.getInputStream(), JsonNode.class); conn.disconnect(); return authTokenJson; } catch (Exception e) { conn.disconnect(); throw new RuntimeException("Failed to generate OAuth Token"); } } private static String callRestURL() throws Exception { HttpURLConnection conn = null; try { trustAllCert(); JsonNode authTokenResponse = getAuthTokenDetails(); URL url = new URL(projectUrl); conn = (HttpURLConnection) url.openConnection(); System.out.println("Token Generated : " + authTokenResponse.get("accessToken").asText()); conn.setRequestProperty("Authorization", "Bearer " + authTokenResponse.get("accessToken").asText()); conn.setRequestProperty("x-prime-tenant-code", authTokenResponse.get("primeTenantCode").asText()); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Accept", "application/json"); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Version", version); String input = "{\"projectCode\":\"SampleProject\", \"status\":\"ACTIVE\", \"projectName\":\"SampleProject\",\"workspaceId\": " + workspaceId + ", \"pegRate\":12}"; OutputStream os = conn.getOutputStream(); os.write(input.getBytes("UTF-8")); os.flush(); if (conn.getResponseCode() != 200 && conn.getResponseCode() != 201 && conn.getResponseCode() != 204 && conn.getResponseCode() != 202 && conn.getResponseCode() != 203) { throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode() + " Error: " + readStreamData(conn.getErrorStream())); } return readStreamData(conn.getInputStream()); } finally { if (conn != null) { conn.disconnect(); } } } private static String readStreamData(InputStream is) throws IOException { try (BufferedReader br = new BufferedReader(new InputStreamReader(is))) { String output; StringBuilder buff = new StringBuilder(); while ((output = br.readLine()) != null) { buff.append(output); } return buff.toString(); } } private static void trustAllCert() throws NoSuchAlgorithmException, KeyManagementException { // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { @Override public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkClientTrusted(X509Certificate[] certs, String authType) { } @Override public void checkServerTrusted(X509Certificate[] certs, String authType) { } } }; // Install the all-trusting trust manager SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); // Create all-trusting host name verifier HostnameVerifier allHostsValid = (hostname, session) -> true; // Install the all-trusting host verifier HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid); } }