Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove headers in a NSMutableURLRequest?

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.

like image 361
Gurpartap Singh Avatar asked Dec 13 '11 06:12

Gurpartap Singh


People also ask

How do I remove a header request?

The dp:remove-http-request-header function removes a specific header field and its associated value from the protocol header of a client request. If the client request contains the header field that is identified by the name parameter, the function removes this header field from the client request.

What is NSMutableURLRequest?

NSMutableURLRequest is a subclass of NSURLRequest that allows you to change the request's properties. NSMutableURLRequest only represents information about the request. Use other classes, such as NSURLSession , to send the request to a server.


3 Answers

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.

like image 165
The Nicow Avatar answered Oct 17 '22 22:10

The Nicow


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"];
like image 4
Antoine Avatar answered Oct 17 '22 20:10

Antoine


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"];
like image 3
nburk Avatar answered Oct 17 '22 22:10

nburk