7

How can I make a request that contains no headers fields? The requests are being sent to my own server implementation from scratch, which doesn't care about header fields. The request will at most contain only a post body. Let me know if I'm missing something logical.

Please don't tell me about ASIHTTPRequest. Thank you.

Gurpartap Singh
  • 2,744
  • 1
  • 26
  • 30
  • Have you ever find an answer to this? I'm trying to remove all headers and the responses here don't seem to work today – Jan Oct 20 '17 at 15:28

4 Answers4

10

As I wanted to remove specific header on a NSMutableURLRequest, I've just found that calling setValue:forHTTPHeaderField: with a nil value actually removes it.

It's not documented by Apple, but it seems quite logical.

The Nicow
  • 101
  • 1
  • 3
  • 4
    Just for those who found this page with google -- It's not working anymore (I'm using 10.8 sdk). If you set it to nil, User-Agent will not be changed at all. – wecing Nov 05 '12 at 03:39
  • It works for me on iOS 6.1 SDK with a custom header (I did not test User-Agent). – Marián Černý Jun 10 '13 at 08:25
4

For me the code

[request addValue:@"" forHTTPHeaderField:@"User-Agent"];

only added an empty string instead of cleaning the User-Agent. Instead, using setValue fixed it:

[request setValue:@"" forHTTPHeaderField:@"User-Agent"];
Antoine
  • 23,526
  • 11
  • 88
  • 94
3

I found that for some of the header fields ("User-Agent" is one of them), setting the header value to nil using

[request addValue:nil forHTTPHeaderField:@"User-Agent"];

doesn't actually remove the header field, but rather sets it to a default value!

If you want to actually remove the content, it is enough setting the value to an empty string with

[request addValue:@"" forHTTPHeaderField:@"User-Agent"];
nburk
  • 22,409
  • 18
  • 87
  • 132
1
  1. Why not just ignore them, if you control the server implementation?

  2. Does [request setAllHTTPHeaderFields:[NSDictionary dictionary]] work?

  3. If #2 didn't work, try making your own subclass that always returns an empty dictionary from the allHTTPHeaderFields method, and nil from the valueForHTTPHeaderField: method. But NSURLConnection might make a copy of your request, so you might have to override copyWithZone: also.

rob mayoff
  • 375,296
  • 67
  • 796
  • 848