Capture response headers for HttpUrlConnection
MODIFY
instrumentation/http-url-connection/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/httpurlconnection/HttpUrlConnectionInstrumentation.java
instrumentation/http-url-connection/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/httpurlconnection/HttpUrlConnectionInstrumentation.java
@@ -74,6 +74,11 @@ public class HttpUrlConnectionInstrumentation implements TypeInstrumentation {
// top-level HttpURLConnection calls
return;
}
+ // double increment on first entry is used to prevent infinite recursion in case end()
+ // captures response headers due to HttpUrlConnection.getHeaderField() calling
+ // HttpUrlConnection.getInputStream() which then enters this advice again
+ callDepth.getAndIncrement();
+
Context parentContext = currentContext();
if (!instrumenter().shouldStart(parentContext, connection)) {
return;
@@ -108,12 +113,17 @@ public class HttpUrlConnectionInstrumentation implements TypeInstrumentation {
@Advice.Local("otelHttpUrlState") HttpUrlState httpUrlState,
@Advice.Local("otelScope") Scope scope,
@Advice.Local("otelCallDepth") CallDepth callDepth) {
- if (callDepth.decrementAndGet() > 0) {
+ // checking against 1 instead of against 0, because of the double increment which is used to
+ // prevent infinite recursion in case end() captures response headers
+ if (callDepth.decrementAndGet() > 1) {
return;
}
if (scope == null) {
+ // need to perform the second decrement here since bailing out early
+ callDepth.decrementAndGet();
return;
}
+ try {
scope.close();
if (throwable != null) {
@@ -138,6 +148,11 @@ public class HttpUrlConnectionInstrumentation implements TypeInstrumentation {
instrumenter().end(httpUrlState.context, connection, responseCode, null);
httpUrlState.finished = true;
}
+ } finally {
+ // double increment is used to prevent infinite recursion in case end() captures response
+ // headers
+ callDepth.decrementAndGet();
+ }
}
}

MODIFY
instrumentation/http-url-connection/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/httpurlconnection/HttpUrlHttpAttributesExtractor.java
instrumentation/http-url-connection/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/httpurlconnection/HttpUrlHttpAttributesExtractor.java
@@ -72,6 +72,7 @@ class HttpUrlHttpAttributesExtractor
@Override
protected List<String> responseHeader(
HttpURLConnection connection, Integer statusCode, String name) {
- return emptyList();
+ String value = connection.getHeaderField(name);
+ return value == null ? emptyList() : singletonList(value);
}
}

Capture response headers for HttpUrlConnection (#4417)