View Javadoc
1   package org.kuali.ole;
2   
3   import org.slf4j.Logger;
4   import org.slf4j.LoggerFactory;
5   import java.io.BufferedReader;
6   import java.io.IOException;
7   import java.io.InputStreamReader;
8   import java.net.HttpURLConnection;
9   import java.net.URL;
10  
11  /**
12   * Created by jayabharathreddy on 12/9/14.
13   */
14  public class GOKBConnectionReader {
15      private static final Logger LOG = LoggerFactory.getLogger(GOKBConnectionReader.class);
16  
17      private GOKBConnectionReader() {}
18  
19      public static GOKBConnectionReader getInstance() {
20          return new GOKBConnectionReader();
21      }
22  
23      /**
24       * Returns the output from the given URL.
25       * <p/>
26       * I tried to hide some of the ugliness of the exception-handling
27       * in this method, and just return a high level Exception from here.
28       * Modify this behavior as desired.
29       *
30       * @param desiredUrl
31       * @return
32       * @throws Exception
33       */
34      public String doHttpUrlConnectionAction(String desiredUrl)
35              throws Exception {
36          URL url = null;
37          BufferedReader reader = null;
38          StringBuilder stringBuilder;
39  
40          try {
41              // create the HttpURLConnection
42              url = new URL(desiredUrl);
43              HttpURLConnection connection = (HttpURLConnection) url.openConnection();
44  
45              // just want to do an HTTP GET here
46              connection.setRequestMethod("GET");
47  
48              // uncomment this if you want to write output to this url
49              //connection.setDoOutput(true);
50  
51              // give it 15 seconds to respond
52  //            connection.setReadTimeout(60 * 1000);
53              connection.connect();
54  
55              // read the output from the server
56              reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
57              stringBuilder = new StringBuilder();
58  
59              String line = null;
60              while ((line = reader.readLine()) != null) {
61                  stringBuilder.append(line + "\n");
62              }
63              return stringBuilder.toString();
64          } catch (Exception e) {
65              e.printStackTrace();
66              throw e;
67          } finally {
68              // close the reader; this can throw an exception too, so
69              // wrap it in another try/catch block.
70              if (reader != null) {
71                  try {
72                      reader.close();
73                  } catch (IOException ioe) {
74                      ioe.printStackTrace();
75                  }
76              }
77          }
78      }
79  }