3

I need to send request to my server without http headers with NSMutableURLRequest and NSMutableURLConnection. I found this to remove content of header [request setValue:@"" forHTTPHeaderField:@"User-Agent"];, but I need to delete all header. Now:

GET / HTTP/1.1
Host: 127.0.0.1:5555
Accept: */*
Accept-Language: en-us
Connection: keep-alive
Accept-Encoding: gzip, deflate
User-Agent: 

Need:

Custom text like "Hello"

Code:

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 
Vlad
  • 1,541
  • 1
  • 21
  • 27

3 Answers3

1

Assuming you have implemented an NSURLConnectionDataDelegate, you have the opportunity to copy and modify the request before it is sent:

- (NSURLRequest *)connection: (NSURLConnection *)inConnection
             willSendRequest: (NSURLRequest *)inRequest
            redirectResponse: (NSURLResponse *)inRedirectResponse;
{
  if (inRequest) {
    NSMutableURLRequest *modifiedRequest = [inRequest mutableCopy];
    [modifiedRequest setValue:nil forHTTPHeaderField:@"User-Agent"];
    // or whatever code you need to nil out unwanted header fields
    return modifiedRequest;
  } else {
    return nil;
  }
}

The description of this delegate method makes it seem like it is only called in the case of redirects, but it is actually called before every request is issued (up to and including macOS 10.12). In fact, for a redirect it is called twice -- once with the original URL and once with the target of the redirect.

From my experimentation, it is not possible to remove User-Agent, Accept-Encoding, or Accept-Language prior to calling NSURLConnection initWithRequest.

Mike
  • 964
  • 9
  • 9
0

I really don't know why you want to delete the header as there might be some default header field. But I guess you can use this

NSURLConnection *connection;
NSURL* url=[NSURL URLWithString:@"your url"];

NSMutableURLRequest *request = [NSMutableURLRequest 
requestWithURL:[url standardizedURL]];

//set http method GET OR POST OR WHATEVER
[request setHTTPMethod:@"GET"];
 connection=[NSURLConnection connectionWithRequest:request delegate:self];

I think it will work and header will be sent as a null

Rajan Maheshwari
  • 14,465
  • 6
  • 64
  • 98
0

Try this:

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:self.URL];
for (NSString *key in [request.allHTTPHeaderFields allKeys]) {
    [request setValue:nil forHTTPHeaderField:key];
}
Alexander
  • 157
  • 2
  • 6