While working on a project which uses the TIdHTTP component, I realized I needed to eliminate certain HTTP headers from being sent.

After examining the logic flow in Indy's TIdHTTP component, I realized that all I needed to do to manipulate HTTP headers is to create a TIdHttpRequest descendant, and override the SetHeaders method.

Then, before making a call to any of the TIdHTTP.Get methods, assign an instance of the TIdHttpRequest descendant to the TIdHTTP.Request property, like so:

  IdHTTP1.Request.Free;

1
2
IdHTTP1.Request.Free;
IdHTTP1.Request := TIdHTTPRequestReplacement.Create(IdHTTP1);

Here's what the SetHeaders method looks like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
procedure TIdHTTPRequestReplacement.SetHeaders;
var
  I: Integer;
  LHeader: string;
  SL: TStringList;
begin
  inherited;
  SL := TStringList.Create;
  try
 
// Clear any headers that is not User-Agent, Host, etc...
    for I := 0 to RawHeaders.Count-1 do
      begin
        LHeader := RawHeaders.Names[ I ];
        if (LHeader<>'User-Agent') and (LHeader<>'Host') and
          (LHeader<>'xxx') and (LHeader<>'yyy') then
          SL.Add(LHeader);
      end;
 
// Pretend we're some other browser
    RawHeaders.Values['User-Agent'] := 'custom user-agent';
 
    for LHeader in SL do
      RawHeaders.Values[LHeader] := '';
  finally
    SL.Free;
  end;
end;