将HTTP标头添加到NSURLRequest

时间:2010-11-24 09:18:08

标签: iphone objective-c http nsurlrequest

有没有办法将HTTP标头添加到NSURLRequest对象?我曾经使用以下代码在NSMutableURLRequest添加它们

[request addValue:@"PC" forHTTPHeaderField:@"machineName"]

3 个答案:

答案 0 :(得分:80)

我认为您无法修改NSURLRequest的HTTP标头。我想您正在尝试修改未初始化的NSURLRequest对象?

您可以创建mutableCopy您的请求,然后使用以下方法设置标题字段:

 -(void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field.

之后,您可以copy将可变请求重新发送回NSURLRequest变量。

编辑:添加了以下示例

/* Create request variable containing our immutable request
 * This could also be a paramter of your method */
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.stackoverflow.com"]];

// Create a mutable copy of the immutable request and add more headers
NSMutableURLRequest *mutableRequest = [request mutableCopy];
[mutableRequest addValue:@"Hless" forHTTPHeaderField:@"X-user-nick"];

// Now set our request variable with an (immutable) copy of the altered request
request = [mutableRequest copy];

// Log the output to make sure our new headers are there    
NSLog(@"%@", request.allHTTPHeaderFields);

答案 1 :(得分:7)

已经回答(并且感谢那些答案),但这是一个更简单的例子:

NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
[request setValue:@"es" forHTTPHeaderField:@"Accept-Language"];

答案 2 :(得分:5)

NSString *urlString = @"http://10.28.79.63:3000/testing";

NSMutableURLRequest *imageRequest = [[NSMutableURLRequest alloc] init] ;
[imageRequest setURL:[NSURL URLWithString:urlString]];
[imageRequest setHTTPMethod:@"POST"];

NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"];
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];

[imageRequest setValue:contentType forHTTPHeaderField: @"content-Type"]; 
NSMutableData *body = [NSMutableData dataWithCapacity:[imageData length] + 512];
[body appendData:[[NSString stringWithFormat:@"--%@\r\n",boundary]dataUsingEncoding:NSUTF8StringEncoding]]; 

//Here u adds the Headers which will be posted in body 

[body appendData:[[NSString stringWithString:@"Content-Disposition: form-data; content-type: application/octet-stream; name=\"userfile\"; filename=\"inLove.mp4\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];


[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

[imageRequest setHTTPBody:body];
NSURLConnection * theConnection = [[NSURLConnection alloc] initWithRequest:imageRequest 
                                                delegate:self];