View Javadoc
1   package com.github.davidmoten.aws.lw.client.internal.auth;
2   
3   import java.io.BufferedReader;
4   import java.io.IOException;
5   import java.io.InputStream;
6   import java.io.InputStreamReader;
7   import java.net.HttpURLConnection;
8   import java.net.URL;
9   import java.nio.charset.StandardCharsets;
10  import java.util.Map;
11  
12  import com.github.davidmoten.aws.lw.client.internal.util.Util;
13  
14  /**
15   * Various Http helper routines
16   */
17  public class HttpUtils {
18  
19      private static final int CONNECT_TIMEOUT_MS = 30000;
20      private static final int READ_TIMEOUT_MS = 5 * 60000;
21  
22      public static String executeHttpRequest(HttpURLConnection connection) {
23          try {
24              // Get Response
25              InputStream is;
26              try {
27                  is = connection.getInputStream();
28              } catch (IOException e) {
29                  is = connection.getErrorStream();
30              }
31  
32              try (BufferedReader rd = new BufferedReader(
33                      new InputStreamReader(is, StandardCharsets.UTF_8))) {
34                  String line;
35                  StringBuffer response = new StringBuffer();
36                  while ((line = rd.readLine()) != null) {
37                      response.append(line);
38                      response.append('\r');
39                  }
40                  return response.toString();
41              }
42          } catch (IOException | RuntimeException e) {
43              throw new RuntimeException("Request failed. " + e.getMessage(), e);
44          } finally {
45              if (connection != null) {
46                  connection.disconnect();
47              }
48          }
49      }
50  
51      public static HttpURLConnection createHttpConnection(URL endpointUrl, String httpMethod,
52              Map<String, String> headers) throws IOException {
53          return Util.createHttpConnection(endpointUrl, httpMethod, headers, CONNECT_TIMEOUT_MS,
54                  READ_TIMEOUT_MS);
55      }
56  
57  }