Processing REST API requests to the IBM Streams security service
To access information from the IBM® Streams security service by using the REST API, your application must send a valid HTTP request. The application must then handle the HTTP response.
About this task
Each resource can be identified by a uniform resource identifier (URI). You can add query parameters to the URI to tailor and filter response content. The REST API supports standard HTTP methods for accessing the resource that is identified by the URI.
The Streams REST API uses the JavaScript Object Notation (JSON) format for message content.
Procedure
Example
myRealm
security realm. In this example, user authentication
is handled by using HTTP basic
authentication.import java.io.*;
import java.net.*;
import javax.net.ssl.*;
import javax.xml.bind.DatatypeConverter;
import com.ibm.json.java.JSONArray;
import com.ibm.json.java.JSONObject;
public class RestBasic {
public static void main (String[] args) {
try {
System.setProperty("javax.net.ssl.trustStore", ".\\ibmjsse2.jks");
System.setProperty("javax.net.ssl.trustStorePassword", "ibmpassw0rd");
HostnameVerifier hv = new HostnameVerifier() {
public boolean verify(String urlHostName, SSLSession session) {
return true; // trust all hosts that supply the Streams certificate
}
};
HttpsURLConnection.setDefaultHostnameVerifier(hv);
// Retain cookies between requests
CookieManager cm = new CookieManager();
CookieHandler.setDefault(cm);
URL url = new URL("https://server5.ibm.com:8456/streams/rest/security/realms/myRealm/accesstokens");
String userInfo = "bsmith" + ":" + new String("secret");
String authToken = "Basic " + DatatypeConverter.printBase64Binary(userInfo.getBytes());
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
JSONObject json = new JSONObject();
JSONArray audience = new JSONArray();
json.put("audience", audience);
audience.put("streams");
String request = json.serialize();
conn.setRequestProperty("Authorization", authToken);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Content-Length", Long.toString(request.length()));
conn.setDoOutput(true);
conn.connect();
OutputStream os = http.getOutputStream();
os.write(request.getBytes());
os.close();
System.out.println("Response code: " + conn.getResponseCode());
System.out.println("Content type: " + conn.getHeaderField("Content-Type"));
InputStream responseStream = conn.getInputStream();
InputStreamReader responseStreamReader = new InputStreamReader(responseStream);
JSONObject jsonResult = JSONObject.parse(responseStreamReader);
String accessToken = (String)jsonResult.get("accessToken");
System.out.println("accessToken = " + accessToken);
conn.disconnect();
}
catch (Exception e) {
System.out.println("Exception: " + e.getMessage());
}
}
}