addDefaultHeaders method

void addDefaultHeaders(
  1. HttpHeaders headers,
  2. MediaType? contentType
)

Adds default headers to the HTTP message if not already present.

Parameters

  • headers: The HTTP headers to modify
  • contentType: The content type to set if no Content-Type is present

Header Strategy

This method follows a conservative approach:

  • Only sets Content-Type if not already specified
  • Respects existing headers to avoid overriding user-set values
  • Uses the provided contentType or falls back to first supported media type

Example

@override
Future<void> write(Object object, MediaType? contentType, HttpOutputMessage outputMessage) async {
  final headers = outputMessage.getHeaders();
  
  // Set default headers if needed
  addDefaultHeaders(headers, contentType);
  
  // Now proceed with writing the body
  await writeInternal(object, outputMessage);
}

Implementation

void addDefaultHeaders(HttpHeaders headers, MediaType? contentType) {
  if (headers.getContentType() == null && contentType != null) {
    headers.setContentType(contentType);
  }
}