Add default headers also when custom retry policy or headers are provided
@@ -79,12 +79,7 @@ public final class EC2CredentialsUtils {
* If the requested service is not found.
*/
public String readResource(URI endpoint) throws IOException {
- Map<String, String> headers = new HashMap<String, String>();
- headers.put("User-Agent", USER_AGENT);
- headers.put("Accept", "*/*");
- headers.put("Connection", "keep-alive");
-
- return readResource(endpoint, CredentialsEndpointRetryPolicy.NO_RETRY, headers);
+ return readResource(endpoint, CredentialsEndpointRetryPolicy.NO_RETRY, null);
}
/**
@@ -111,6 +106,8 @@ public final class EC2CredentialsUtils {
int retriesAttempted = 0;
InputStream inputStream = null;
+ headers = addDefaultHeaders(headers);
+
while (true) {
try {
HttpURLConnection connection = connectionUtils.connectToEndpoint(endpoint, headers);
@@ -141,6 +138,24 @@ public final class EC2CredentialsUtils {
}
+ private Map<String,String> addDefaultHeaders(Map<String,String> headers) {
+ HashMap<String, String> map = new HashMap<String, String>();
+ if (headers != null) {
+ map.putAll(headers);
+ }
+
+ putIfAbsent(map,"User-Agent", USER_AGENT);
+ putIfAbsent(map,"Accept", "*/*");
+ putIfAbsent(map,"Connection", "keep-alive");
+ return map;
+ }
+
+ private <K,V> void putIfAbsent(Map<K,V> map, K key, V value) {
+ if (map.get(key) == null) {
+ map.put(key, value);
+ }
+ }
+
private void handleErrorResponse(InputStream errorStream, int statusCode, String responseMessage) throws IOException {
String errorCode = null;
