How to remove headers in NSMutableURLRequest?

How can I make a request that does not contain header fields? Requests are sent to my own server implementation from scratch, which does not apply to header fields. The request in most cases will contain only the message body. Let me know if I miss something logical.

Please do not tell me about ASIHTTPRequest. Thanks.

+6
source share
4 answers

As I wanted to remove a specific header in NSMutableURLRequest, I just found that calling setValue: forHTTPHeaderField: with a null value actually deletes it.

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

+9
source
  • Why not just ignore them if you control the server implementation?

  • Does [request setAllHTTPHeaderFields:[NSDictionary dictionary]] ?

  • If # 2 does not work, try making your own subclass that always returns an empty dictionary from the allHTTPHeaderFields method and nil from the valueForHTTPHeaderField: method. But NSURLConnection can make a copy of your request, so you might also need to override copyWithZone:

+1
source

Code for me

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

added blank line instead of clearing User-Agent. Instead, using setValue, he fixed this:

 [request setValue:@"" forHTTPHeaderField:@"User-Agent"]; 
+1
source

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

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

doesn’t actually delete the header field, but sets it by default!

If you want to delete the content, just set the value to an empty string with

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

Source: https://habr.com/ru/post/903653/


All Articles