Samples JDK
HttpsClientTest.java
1 package com.freemindcafe.apache.commons;
2 import java.io.IOException;
3 import java.util.regex.Matcher;
4 import java.util.regex.Pattern;
5 
6 import org.apache.commons.httpclient.HttpClient;
7 import org.apache.commons.httpclient.NameValuePair;
8 import org.apache.commons.httpclient.methods.PostMethod;
9 import org.apache.log4j.BasicConfigurator;
10 import org.apache.log4j.Level;
11 import org.apache.log4j.Logger;
12 import org.junit.Test;
13 
14 
15 public class HttpsClientTest
16 {
17 
18  private static final Logger logger = Logger.getLogger (HttpsClientTest.class);
19 
20  @Test
21  public void test()
22  {
23  BasicConfigurator.configure();
24  System.setProperty("javax.net.ssl.trustStore","/home/eip/conf/systemProperties/localhostkeystore");
25  final HttpClient client = new HttpClient();
26 
27  final PostMethod post = new PostMethod("https://nikhil-vm.emeter.com:9443/em-cas/login");
28  String username = "abc";
29 
30  post.setRequestBody(new NameValuePair[] {
31  new NameValuePair("username", username),
32  new NameValuePair("password", "xyz") });
33 
34  try {
35  logger.info("Attempt to get TGT for user [" + username + "]");
36 
37  //change the logging level for content of http message to INFO as in case of DEBUG mode user name and password is getting printed
38  Level oldLevel = Logger.getLogger("httpclient.wire.content").getLevel();
39  Logger.getLogger("httpclient.wire.content").setLevel(Level.INFO);
40 
41  client.executeMethod(post);
42  //switch back to original level.
43  Logger.getLogger("httpclient.wire.content").setLevel(oldLevel);
44 
45  final String response = post.getResponseBodyAsString();
46 
47  switch (post.getStatusCode()) {
48  case 201: {
49  final Matcher matcher = Pattern.compile(".*action=\".*/(.*?)\".*").matcher(response);
50 
51  if (matcher.matches()) {
52  logger.info("result - " + matcher.group(1));
53  }
54 
55  logger.error("Successful ticket granting request, but no ticket found!");
56  logger.error("Response (1k): "
57  + response.substring(0, Math.min(1024, response.length())));
58  break;
59  } default: {
60  logger.error("Invalid response code (" + post.getStatusCode()
61  + ") from CAS server!");
62  logger.error("Response (1k): "
63  + response.substring(0, Math.min(1024, response.length())));
64  break;
65  }
66  }
67  } catch (final IOException e) {
68  logger.error("Exception while trying to get TGT from CAS server for USER - " + username, e);
69  } finally {
70  post.releaseConnection();
71  }
72  logger.info("result - " + "null");
73 
74  }
75 
76 
77 }