Cisco Cisco Workload Automation 6.3 Developer's Guide
14
Using the CWA REST API
Java Client REST API Examples
BufferedReader reader =
new
BufferedReader(
new
InputStreamReader(
conn.getInputStream()));
String resp = "";
String next =
null
;
while
((next = reader.readLine()) !=
null
)
resp += next;
System.
out
.println(resp);
}
Code Example 3 – Session Management Using the Session Cookie
In both previous code examples, the calls establish new sessions on the server. For typical applications that make
repeated calls to the REST API, the best practice is to reuse the established sessions so that the server does not create
excessive number of active sessions, which eventually could cause it to run out of memory.
repeated calls to the REST API, the best practice is to reuse the established sessions so that the server does not create
excessive number of active sessions, which eventually could cause it to run out of memory.
Code Example 3 is an extension of Code Example 1 showing the usages of a cookie for session management.
public static void
tesGetRequestWithSession()
throws
Exception
{
String sessionID =
null
;
for (int
i=0; i<10; i++)
{
URL url =
new
URL(
"http://www.mycompanyscheduler.com:8080/api/tes-6.2/Job.getList"
);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("
GET
");
conn.setDoInput(
true
);
conn.setDoOutput(
true
);
if
(sessionID ==
null
)
{
String userNamePassword = "
myusername:mypassword
";
userNamePassword =
new
String(org.apache.commons.codec.binary.Base64.encodeBase64(userNamePassword
.getBytes()));
conn.setRequestProperty("
Authorization
", userNamePassword);
}
else
{
conn.setRequestProperty("Cookie", sessionID);
}
conn.connect();
BufferedReader reader =
new
BufferedReader(
new
InputStreamReader(
conn.getInputStream()));
String resp = "";
String next =
null
;
while
((next = reader.readLine()) !=
null
)
resp += next;
System.
out
.println(resp);
//extract cookie
String setCookies = conn.getHeaderField(
"Set-Cookie"
);
if
(setCookies !=
null
&& sessionID ==
null
)
{
String cookies[] = setCookies.split(";");
if
(cookies.
length
> 0)
sessionID = cookies[0];
}
}
}