删除NSMutableURLRequest中的HTTP标头

时间:2015-02-07 10:10:54

标签: objective-c http http-headers nsurlconnection nsurlrequest

我需要使用NSMutableURLRequest和NSMutableURLConnection向没有http标头的服务器发送请求。我发现这会删除标题[request setValue:@"" forHTTPHeaderField:@"User-Agent"];的内容,但我需要删除所有标题。 现在:

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

需要:

Custom text like "Hello"

代码:

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 

3 个答案:

答案 0 :(得分:0)

我真的不知道你为什么要删除标题,因为可能有一些默认的标题字段。但我猜你可以用这个

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];

我认为它会起作用,标题将作为空

发送

答案 1 :(得分:0)

试试这个:

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

答案 2 :(得分:0)

假设您已实施NSURLConnectionDataDelegate,您可以在发送请求之前复制和修改请求:

- (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;
  }
}

这种委托方法的描述使得它似乎只在重定向的情况下被调用,但它实际上是在每个请求发出之前调用的(直到并包括macOS 10.12)。事实上,对于重定向,它被调用两次 - 一次使用原始URL,一次使用重定向目标。

根据我的实验,在致电User-Agent Accept-Encoding之前无法删除Accept-LanguageNSURLConnectioninitWithRequest