How to remove headers in a NSMutableURLRequest?
Asked Answered
L

4

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.

Lawley answered 13/12, 2011 at 6:1 Comment(1)
Have you ever find an answer to this? I'm trying to remove all headers and the responses here don't seem to work todayElephantine
T
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.

Trustless answered 26/5, 2012 at 13:4 Comment(2)
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.Aden
It works for me on iOS 6.1 SDK with a custom header (I did not test User-Agent).Brabazon
B
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"];
Bruner answered 24/10, 2014 at 9:4 Comment(2)
Just a note that this is the correct answer. addValue will append the new value to the previous value, comma delimited. setValue will replace the previous value.Cariecaries
Echo that, this is still the correct answer as of iOS 11.3Serinaserine
B
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"];
Barramunda answered 4/2, 2014 at 11:10 Comment(1)
I actually found using nil removes the header, at least on MacOS.Sheridan
T
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.

Teratism answered 13/12, 2011 at 6:9 Comment(2)
#1 Every byte saved matters for this implementation.Lawley
#2 won't work because it doesn't override the internal dictionary. It's just overriding the keys, if any. I'll look at subclassing and let you know if that helps.Lawley

© 2022 - 2024 — McMap. All rights reserved.